题目描述
给你一棵二叉树的根节点 root
,翻转这棵二叉树,并返回其根节点。
示例
1 2
| 输入:root = [4,2,7,1,3,6,9] 输出:[4,7,2,9,6,3,1]
|
提示:
- 树中节点数目范围在
[0, 100]
内
-100 <= Node.val <= 100
题解
方法1:遍历
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| func invertTree(_ root: TreeNode?) -> TreeNode? { guard let root = root else { return nil } var queue = [root] while !queue.isEmpty { let cur = queue.removeFirst() let temp = cur.left cur.left = cur.right cur.right = temp if let left = cur.left { queue.append(left) } if let right = cur.right { queue.append(right) } } return root }
|
方法2:递归
1 2 3 4 5 6 7 8 9 10 11 12 13
| func invertTree2(_ root: TreeNode?) -> TreeNode? { guard let root = root else { return root } let temp = root.left root.left = root.right root.right = temp invertTree2(root.left) invertTree2(root.right) return root }
|