forked from akshitagit/JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTree.js
More file actions
91 lines (81 loc) · 1.66 KB
/
BinaryTree.js
File metadata and controls
91 lines (81 loc) · 1.66 KB
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
class Node {
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
}
}
class BinaryTree {
constructor() {
this.root = null;
}
insert(data) {
const newNode = new Node(data);
if (this.root === null) {
this.root = newNode;
} else {
this.insertNode(this.root, newNode);
}
}
insertNode(node, newNode) {
if (newNode.data < node.data) {
if (node.left === null) {
node.left = newNode;
} else {
this.insertNode(node.left, newNode);
}
} else {
if (node.right === null) {
node.right = newNode;
} else {
this.insertNode(node.right, newNode);
}
}
}
remove(data) {
this.root = this.removeNode(this.root, data);
}
removeNode(node, key) {
if (node === null) {
return null;
} else if (key < node.data) {
node.left = this.removeNode(node.left, key);
} else if (key > node.data) {
node.right = this.removeNode(node.right, key);
} else {
if (node.left === null && node.right === null) {
node = null;
} else if (node.left === null) {
node = node.right;
} else if (node.right === null) {
node = node.left;
} else {
const childRight = node.right;
this.insertNode(childRight, node.left);
node = childRight;
}
}
return node;
}
preorder(fn, node = this.root) {
if (node !== null) {
fn(node);
this.preorder(fn, node.left);
this.preorder(fn, node.right);
}
}
inorder(fn, node = this.root) {
if (node !== null) {
this.preorder(fn, node.left);
fn(node);
this.preorder(fn, node.right);
}
}
postorder(fn, node = this.root) {
if (node !== null) {
this.preorder(fn, node.left);
this.preorder(fn, node.right);
fn(node);
}
}
}