翻转一棵二叉树。
示例:
输入:
4
/ \
2 7
/ \ / \
1 3 6 9
输出:
4
/ \
7 2
/ \ / \
9 6 3 1
solution:
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {TreeNode}
*/
var invertTree = function(root) {
if (!root) return null
if (root.left || root.right) {
const temp = invertTree(root.left)
root.left = invertTree(root.right)
root.right = temp
return root
} else {
return root
}
};
还有一种更巧妙的方法,利用了解构赋值的特性,省去了temp的临时变量存储
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {TreeNode}
*/
var invertTree = function(root) {
if (root !== null) {
[root.left, root.right] = [invertTree(root.right), invertTree(root.left)]
}
return root
};