问题描述
Given the root of a binary tree, invert the tree, and return its root.
Example:

1 2
| Input: root = [4,2,7,1,3,6,9] Output: [4,7,2,9,6,3,1]
|
Constraints:
- The number of nodes in the tree is in the range
[0, 100].
-100 <= Node.val <= 100
解答
方法一:递归
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
const invertTree = function (root) { if (!root) { return root }
let temp = root.left root.left = root.right root.right = temp
invertTree(root.left) invertTree(root.right)
return root }
|
方法二:层序遍历
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
|
const invertTree2 = function (root) { if (!root) { return root }
let queue = [root]
while (queue.length) { let curNode = queue.shift() let temp = curNode.left curNode.left = curNode.right curNode.right = temp if (curNode.left) { queue.push(curNode.left) } if (curNode.right) { queue.push(curNode.right) } }
return root }
|