Skip to content

Commit 2c66563

Browse files
authored
Invert binary tree
1 parent 8cd4119 commit 2c66563

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

invertTree.js

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
/**
2+
*
3+
* https://twitter.com/mxcl/status/608682016205344768
4+
*
5+
* Task: invert binary tree
6+
*
7+
* This:
8+
* 4
9+
* / \
10+
* 2 7
11+
* / \ / \
12+
* 1 3 6 9
13+
*
14+
* will turn into this:
15+
*
16+
* 4
17+
* / \
18+
* 7 2
19+
* / \ / \
20+
* 9 6 3 1
21+
*
22+
*/
23+
24+
var tree = {
25+
value: 4,
26+
left: {
27+
value: 2,
28+
left: {
29+
value: 1
30+
},
31+
right: {
32+
value: 3
33+
}
34+
},
35+
right: {
36+
value: 7,
37+
left: {
38+
value: 6
39+
},
40+
right: {
41+
value: 9
42+
}
43+
}
44+
};
45+
46+
function invertTree(node) {
47+
if (!node) return false;
48+
49+
var right = invertTree(node.right);
50+
var left = invertTree(node.left);
51+
52+
if (left) node.left = right;
53+
if (right) node.right = left;
54+
55+
return node;
56+
}
57+
58+
console.log(invertTree(tree));

0 commit comments

Comments
 (0)