-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfind_columns_binary_tree.js
100 lines (84 loc) · 2.28 KB
/
find_columns_binary_tree.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
// ===============================================================================================
// Prepration
class BinaryTreeNode {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
//... build binary tree
const btreeconfig = [70, 60, 76, 58, 63, 74, 80, null, 59, null, null, null, null, null, 88];
const root = new BinaryTreeNode(btreeconfig[0]);
const stack = [root];
let stackPtr = 0;
let flag = "left";
for (let i = 1; i < btreeconfig.length; i++) {
const val = btreeconfig[i];
const node = new BinaryTreeNode(val);
if (flag === "left") {
if (val !== null) stack[stackPtr].left = node;
flag = "right";
} else {
if (val !== null) stack[stackPtr].right = node;
flag = "left";
stackPtr++;
}
stack.push(node);
}
// ===============================================================================================
// ===============================================================================================
//Double Linked List
class DllNode {
value = null;
child = null;
parent = null;
constructor(val) {
this.value = val;
}
insertChild(newChild) {
const oldChild = this.child;
this.child = newChild;
newChild.parent = this;
if (oldChild) {
newChild.child = oldChild;
oldChild.parent = newChild;
}
}
insertParent(newParent) {
const oldParent = this.parent;
this.parent = newParent;
newParent.child = this;
if (oldParent) {
newParent.parent = oldParent;
oldParent.child = newParent;
}
}
}
// THE Solution
function parser(node) {
if (!node) return;
let left, right;
const dllNode = new DllNode(node.value);
if (node.left) {
left = parser(node.left);
while(left.child) {
left = left.child
}
dllNode.insertParent(left);
}
if (node.right) {
right = parser(node.right);
while(right.parent) {
right = right.parent
}
dllNode.insertChild(right);
}
return dllNode;
}
let d = parser(root);
while (d.parent) d = d.parent;
while (d) {
console.log(d.value);
d = d.child;
}