-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinvertTree.js
More file actions
58 lines (52 loc) · 722 Bytes
/
invertTree.js
File metadata and controls
58 lines (52 loc) · 722 Bytes
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
55
56
57
58
/**
*
* https://twitter.com/mxcl/status/608682016205344768
*
* Task: invert binary tree
*
* This:
* 4
* / \
* 2 7
* / \ / \
* 1 3 6 9
*
* will turn into this:
*
* 4
* / \
* 7 2
* / \ / \
* 9 6 3 1
*
*/
var tree = {
value: 4,
left: {
value: 2,
left: {
value: 1
},
right: {
value: 3
}
},
right: {
value: 7,
left: {
value: 6
},
right: {
value: 9
}
}
};
function invertTree(node) {
if (!node) return false;
var right = invertTree(node.right);
var left = invertTree(node.left);
if (left) node.left = right;
if (right) node.right = left;
return node;
}
console.log(invertTree(tree));