-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtreenode.ts
132 lines (116 loc) · 3.36 KB
/
treenode.ts
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
export class TreeNode {
public val: number;
public leftChild: TreeNode;
public rightChild: TreeNode;
public root: TreeNode;
constructor(val: number, leftChild: TreeNode = null, righChild: TreeNode = null) {
this.val = val;
this.leftChild = leftChild;
this.rightChild = righChild;
this.root = this;
}
insert(n: TreeNode, root: TreeNode = this.root) {
if (!root || root.val === null) {
return;
}
if (root.val === n.val) {
return;
}
if (n.val < root.val) {
if (root.leftChild === null) {
root.leftChild = n;
} else {
this.insert(n, root.leftChild);
}
} else {
if (root.rightChild === null) {
root.rightChild = n;
} else {
this.insert(n, root.rightChild);
}
}
}
search(val: number, root: TreeNode = this.root) {
if (!root || !root.val) {
return null;
}
if (root.val === val) {
return root;
}
if (val < root.val) {
return this.search(val, root.leftChild);
} else if (val > root.val) {
return this.search(val, root.rightChild);
}
return 'not found';
}
delete(val: number, root: TreeNode = this.root) {
if (!root || !root.val) {
return;
}
if (val < root.val) {
root.leftChild = this.delete(val, root.leftChild);
return root;
} else if (val > root.val) {
root.rightChild = this.delete(val, root.rightChild);
return root;
} else if (root.val === val) {
if (root.leftChild === null) {
return root.rightChild;
} else if (root.rightChild === null) {
return root.leftChild;
} else {
// find least succesor node and swap
root.rightChild = this.lift(root.rightChild, root);
return root;
}
}
}
lift(n: TreeNode, del: TreeNode) {
if (n.leftChild) {
n.leftChild = this.lift(n.leftChild, del);
return n;
} else {
del.val = n.val;
return n.rightChild;
}
}
inorder(tree: TreeNode = this.root) {
// left, root, right
let t = [];
if (tree.leftChild) {
t = t.concat(this.inorder(tree.leftChild));
}
t.push(tree.val);
if (tree.rightChild) {
t = t.concat(this.inorder(tree.rightChild));
}
return t;
}
postorder(tree: TreeNode = this.root) {
// left, right, root
let t = [];
if (tree.leftChild) {
t = t.concat(this.postorder(tree.leftChild));
}
if (tree.rightChild) {
t = t.concat(this.postorder(tree.rightChild));
}
t.push(tree.val);
return t;
}
preorder(tree: TreeNode = this.root) {
// root, left, right
let t = [];
t.push(tree.val);
if (tree.leftChild) {
t = t.concat(this.preorder(tree.leftChild));
}
if (tree.rightChild) {
t = t.concat(this.preorder(tree.rightChild));
}
return t;
}
toLinkedList() {}
toDoubleLinkedList() {}
}