-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathchangeRootBinaryTree.js
More file actions
64 lines (52 loc) · 1.42 KB
/
changeRootBinaryTree.js
File metadata and controls
64 lines (52 loc) · 1.42 KB
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
59
60
61
62
/**
* // Definition for a Node.
* function Node(val) {
* this.val = val;
* this.left = null;
* this.right = null;
* this.parent = null;
* };
*/
/**
* @param {Node} node
* @return {Node}
*/
var flipBinaryTree = function(root, leaf) {
let path;
let directions;
const reroute = (currentPath, currentDirections, current) => {
if (current === null) {
return;
}
if (current === leaf) {
path = currentPath.slice();
directions = currentDirections.slice();
return;
}
currentPath.push(current.left);
currentDirections.push('left');
reroute(currentPath, currentDirections, current.left);
currentPath.pop();
currentDirections.pop();
currentPath.push(current.right);
currentDirections.push('right');
reroute(currentPath, currentDirections, current.right);
currentPath.pop();
currentDirections.pop();
}
reroute([root], [], root);
for (let i = path.length - 1; i > 0; i--) {
let current = path[i];
let parent = path[i - 1];
let direction = directions[i - 1];
if (current.left !== null) {
current.right = current.left;
current.left = null;
}
current.left = parent;
parent[direction] = null;
parent.parent = current;
}
leaf.parent = null;
return leaf;
};