题目
翻转一棵二叉树。
示例:
输入:
4
/ \
2 7
/ \ / \
1 3 6 9
输出:
4
/ \
7 2
/ \ / \
9 6 3 1
备注: 这个问题是受到 Max Howell 的 原问题 启发的 :
谷歌:我们90%的工程师使用您编写的软件(Homebrew),但是您却无法在面试时在白板上写出翻转二叉树这道题,这太糟糕了。
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/invert-binary-tree 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
JS实现
1、递归
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {TreeNode}
*/
var invertTree = function(root) {
if (root === null) {
return null;
}
//将当前节点的左右子树交换
const temp = root.right;
root.right = root.left;
root.left = temp;
//递归交换当前节点的 左子树
invertTree(root.left);
//递归交换当前节点的 右子树
invertTree(root.right);
return root;
};
2、迭代
var invertTree = function (root) {
if (root === null) {
return null;
}
const q = [];
q.push(root);
while (q.length) {
//从队列中取一个节点,并交换这个节点的左右子树
const temp = q.shift();
const left = temp.left;
temp.left = temp.right;
temp.right = left;
if (temp.left) {
q.push(temp.left);
}
if (temp.right) {
q.push(temp.right);
}
}
return root;
};