本文转载自微信公众号「三分钟学前端」,作者sisterAn。转载本文请联系三分钟学前端公众号。
翻转一棵二叉树。
示例:
输入:
4
/ \
2 7
/ \ / \
1 3 6 9
- 1.
- 2.
- 3.
- 4.
- 5.
输出:
4
/ \
7 2
/ \ / \
9 6 3 1
- 1.
- 2.
- 3.
- 4.
- 5.
遍历+交换左右子树
解题思路: 从根节点开始依次遍历每个节点,然后交换左右子树既可
const invertTree = (root) => {
if(!root) return null
// 先翻转当前节点的左右子树
const 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.
这里采用的是前序遍历,也可以是后序遍历或层序遍历
leetcode:https://leetcode-cn.com/problems/invert-binary-tree