-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcourse-tree-challanges.js
110 lines (99 loc) · 2.14 KB
/
course-tree-challanges.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
100
101
102
103
104
105
106
107
108
109
110
class Node {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
class BinarySearchTree {
constructor() {
this.root = null;
}
insert(val) {
function walk(node) {
if (val > node.value) {
if (!node.right) node.right = new Node(val);
else walk(node.right);
} else {
if (!node.left) node.left = new Node(val);
else walk(node.left);
}
}
walk(this.root);
}
find(val) {
let founded;
function walk(node) {
if (node.value === val) founded = node;
if (founded !== undefined) return;
if (val > node.value) {
if (!node.right) founded = null;
else walk(node.right);
} else {
if (!node.left) founded = null;
else walk(node.left);
}
}
walk(this.root);
return founded;
}
BFS() {
const data = [];
const queue = [this.root];
while (queue.length) {
const curr = queue.shift();
data.push(curr);
if (curr.left) {
queue.push(curr.left);
}
if (curr.right) {
queue.push(curr.right);
}
}
return data;
}
DFSPreOrder() {
const data = [];
function walk(node) {
data.push(node.value);
if (node.left) walk(node.left);
if (node.right) walk(node.right);
}
walk(this.root);
return data;
}
DFSPostOrder() {
const data = [];
function walk(node) {
if (node.left) walk(node.left);
if (node.right) walk(node.right);
data.push(node.value);
}
walk(this.root);
return data;
}
DFSInOrder() {
const data = [];
function walk(node) {
if (node.left) walk(node.left);
data.push(node.value);
if (node.right) walk(node.right);
}
walk(this.root);
return data;
}
}
var tree = new BinarySearchTree();
tree.root = new Node(10);
tree.root.right = new Node(15);
tree.root.right.right = new Node(20);
tree.root.left = new Node(6);
tree.root.left.left = new Node(3);
tree.root.left.right = new Node(8);
// tree.insert(13);
console.log(tree);
tree.find(10);
tree.BFS();
tree.DFSPreOrder();
tree.DFSPostOrder();
tree.DFSInOrder();