LeetCode:Invert Binary Tree(翻转二叉树)

LeetCode:Invert Binary Tree(翻转二叉树)

问题描述

copy自LeetCode

Invert a binary tree.

1
2
3
4
5
     4
/ \
2 7
/ \ / \
1 3 6 9

to

1
2
3
4
5
     4
/ \
7 2
/ \ / \
9 6 3 1

解决方法

这个算法其实不难,在LeetCode中的难易评级也是easy,算法的核心就是递归思想,下面直接上代码,也是笔者在LeetCode中的答案,因为LeetCode不支持oc,只能用js了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/** 
* 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){
return null;
}
root.left = invertTree(root.left);
root.right = invertTree(root.right);

var tempNode = root.left;
root.left = root.right;
root.right = tempNode;
return root;
};
隐藏