-
Notifications
You must be signed in to change notification settings - Fork 279
/
Copy path114 Flatten Binary Tree to Linked List.js
59 lines (50 loc) · 1.29 KB
/
114 Flatten Binary Tree to Linked List.js
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
// Leetcode 114
// Language: Javascript
// Problem: https://leetcode.com/problems/flatten-binary-tree-to-linked-list/
// Author: Chihung Yu
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {void} Do not return anything, modify root in-place instead.
*/
var flatten = function(root) {
var stack = [];
var p = root;
while(p !== null || stack.length !== 0){
if(p.right !== null){
stack.push(p.right);
}
if(p.left !== null){ // [!!!]point of confusing, if null then pop stack
p.right = p.left;
p.left = null;
} else if(stack.length !== 0){
var node = stack.pop();
p.right = node;
}
p = p.right;
}
};
// Recursive solution
var flatten = function(root) {
if(root === null || (root.left === null && root.right === null)) {
return;
}
var rootLeft = root.left;
var rootRight = root.right;
root.left = null;
root.right = null;
flatten(rootLeft);
flatten(rootRight);
root.right = rootLeft;
var aux = root;
while(aux !== null && aux.right !== null) {
aux = aux.right;
}
aux.right = rootRight;
};