Skip to content

Commit 13b5dbd

Browse files
Merge pull request chihungyu1116#5 from ignacio-chiazzo/btToLL
another recursive solution
2 parents 6d34381 + ff610c9 commit 13b5dbd

File tree

1 file changed

+26
-3
lines changed

1 file changed

+26
-3
lines changed

114 Flatten Binary Tree to Linked List.js

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,21 +16,44 @@
1616
var flatten = function(root) {
1717
var stack = [];
1818
var p = root;
19-
19+
2020
while(p !== null || stack.length !== 0){
2121
if(p.right !== null){
2222
stack.push(p.right);
2323
}
24-
24+
2525
if(p.left !== null){ // [!!!]point of confusing, if null then pop stack
2626
p.right = p.left;
2727
p.left = null;
2828
} else if(stack.length !== 0){
2929
var node = stack.pop();
3030
p.right = node;
3131
}
32-
32+
3333
p = p.right;
3434
}
3535
};
3636

37+
// Recursive solution
38+
39+
var flatten = function(root) {
40+
if(root === null || (root.left === null && root.right === null)) {
41+
return;
42+
}
43+
44+
var rootLeft = root.left;
45+
var rootRight = root.right;
46+
root.left = null;
47+
root.right = null;
48+
49+
flatten(rootLeft);
50+
flatten(rootRight);
51+
52+
root.right = rootLeft;
53+
54+
var aux = root;
55+
while(aux !== null && aux.right !== null) {
56+
aux = aux.right;
57+
}
58+
aux.right = rootRight;
59+
};

0 commit comments

Comments
 (0)