Skip to content

Commit 44bb3ba

Browse files
authored
Create 1666-change-the-root-of-a-binary-tree.js
1 parent 7d93443 commit 44bb3ba

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* // Definition for a Node.
3+
* function Node(val) {
4+
* this.val = val;
5+
* this.left = null;
6+
* this.right = null;
7+
* this.parent = null;
8+
* };
9+
*/
10+
11+
/**
12+
* @param {Node} node
13+
* @return {Node}
14+
*/
15+
const flipBinaryTree = function(root, leaf) {
16+
function flip(node, from_node){
17+
// set and break pointers between node and from_node
18+
const p = node.parent
19+
node.parent = from_node
20+
if (node.left === from_node) node.left = null
21+
if (node.right === from_node) node.right = null
22+
23+
// stopping condition
24+
if (node === root) return node
25+
26+
// set right child
27+
if (node.left) node.right = node.left
28+
// set left child
29+
node.left = flip(p, node)
30+
return node
31+
}
32+
return flip(leaf, null)
33+
};

0 commit comments

Comments
 (0)