226 翻转二叉树
Closed this issue · 0 comments
sailei1 commented
翻转一棵二叉树。
示例:
输入:
4
/ \
2 7
/ \ / \
1 3 6 9
输出:
4
/ \
7 2
/ \ / \
9 6 3 1
解法:
左右赋值,中间不动 然后递归
/**
* 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 root;
// }
// let node=root;
// let left=node.left,right=node.right;
// node.left=right;
// node.right=left;
// invertTree(node.left);
// invertTree(node.right);
// return node;
// };
var invertTree = function(root) {
if(!root) return root;
let { left, right,val} = root;
let node ={
val,
left:invertTree(right),
right:invertTree(left),
};
return node;
};