-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path03-DFS-PostOrder.js
73 lines (58 loc) · 1.4 KB
/
03-DFS-PostOrder.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
class Node {
constructor (val) {
this.val = val;
this.left = this.right = null;
}
}
class BinarySearchTree {
constructor () {
this.root = null;
}
insert (val, current = this.root) {
if (!this.root) {
this.root = new Node(val);
return this;
}
if (val === current.val) {
return -1;
}
if (val < current.val) {
if (!current.left) {
current.left = new Node(val);
return this;
}
return this.insert(val, current.left);
} else {
if (!current.right) {
current.right = new Node(val);
return this;
}
return this.insert(val, current.right);
}
}
depthFirstSearchPostOrder () {
const output = [];
(function traverse (node) {
if (node.left) {
traverse(node.left);
}
if (node.right) {
traverse(node.right);
}
output.push(node.val);
})(this.root);
return output;
}
}
const bst = new BinarySearchTree();
// 10
// 6 15
// 3 8 20
bst.insert(10);
bst.insert(6);
bst.insert(15);
bst.insert(3);
bst.insert(8);
bst.insert(20);
// console.log(JSON.stringify(bst, 1));
console.log(bst.depthFirstSearchPostOrder());