forked from proYang/leetcode-js
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path226-Invert-Binary-Tree.js
54 lines (52 loc) · 923 Bytes
/
226-Invert-Binary-Tree.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/**
* https://leetcode.com/problems/invert-binary-tree/description/
* Difficulty:Easy
*
* Invert a binary tree.
* 4
* / \
* 2 7
* / \ / \
* 1 3 6 9
*
* to
*
* 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;
if (!root.left && !root.right) return root;
var left = invertTree(root.right);
var right = invertTree(root.left);
root.left = left;
root.right = right;
return root;
};
console.log(invertTree({
val: 4,
left: {
val: 2,
left: {
val: 1,
left: null,
right: null,
},
right: null
},
right: null
}));