Skip to content

Commit e59fc0a

Browse files
authored
Create Binary Tree Upside Down.js
1 parent d90dbd1 commit e59fc0a

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

Binary Tree Upside Down.js

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/**
2+
Given a binary tree where all the right nodes are either leaf nodes with a sibling (a left node that shares the same parent node) or empty, flip it upside down and turn it into a tree where the original right nodes turned into left leaf nodes. Return the new root.
3+
For example:
4+
Given a binary tree {1,2,3,4,5},
5+
6+
1
7+
/ \
8+
2 3
9+
/ \
10+
4 5
11+
12+
return the root of the binary tree [4,5,2,#,#,3,1].
13+
14+
4
15+
/ \
16+
5 2
17+
/ \
18+
3 1
19+
20+
confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.
21+
*/
22+
/**
23+
* Definition for a binary tree node.
24+
* function TreeNode(val) {
25+
* this.val = val;
26+
* this.left = this.right = null;
27+
* }
28+
*/
29+
/**
30+
* @param {TreeNode} root
31+
* @return {TreeNode}
32+
*/
33+
var upsideDownBinaryTree = function(root) {
34+
if (!root || (!root.left && !root.right)) {
35+
return root;
36+
}
37+
38+
let newRoot = upsideDownBinaryTree(root.left);
39+
40+
root.left.left = root.right;
41+
root.left.right = root;
42+
43+
root.left = null;
44+
root.right = null;
45+
46+
return newRoot;
47+
};

0 commit comments

Comments
 (0)