题目
翻转一棵二叉树。
示例:
输入:
4
/ \
2 7
/ \ / \
1 3 6 9
复制代码
输出:
4
/ \
7 2
/ \ / \
9 6 3 1
复制代码
来源:力扣(LeetCode)leetcode-cn.com/problems/in…
解题思路
- 用分治的思想
- 把根节点的左右子树互换
- 再递归把左、右子树翻转
代码实现
var invertTree = function(root) {
if (!root) return root;
//左右子树互换
[root.left, root.right] = [root.right, root.left]
invertTree(root.left)
invertTree(root.right)
return root
};
复制代码
如有错误欢迎指出,欢迎一起讨论!