-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbinary_tree.ts
72 lines (63 loc) · 1.37 KB
/
binary_tree.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
class TreeNode {
value: number
left: TreeNode | null
right: TreeNode | null
constructor(value: number) {
this.value = value
this.left = null
this.right = null
}
}
class BinaryTree {
private root: TreeNode | null
constructor() {
this.root = null
}
add(node: TreeNode) {
if (!this.root) {
this.root = node
} else {
this.insertNode(this.root, node)
}
}
private insertNode(current: TreeNode, node: TreeNode) {
if (node.value < current.value) {
if (!current.left) {
current.left = node
} else {
this.insertNode(current.left, node)
}
} else {
if (!current.right) {
current.right = node
} else {
this.insertNode(current.right, node)
}
}
}
print() {
console.log('====================================')
console.log(this.root)
console.log('====================================')
}
inverse() {
// if (this.root) {
this.inverseTree(this.root!)
// }
}
private inverseTree(current: TreeNode) {
if (current) {
const left = current.left
const right = current.right
current.left = right
current.right = left
if (current.left) {
this.inverseTree(current!.left)
}
if (current.right) {
this.inverseTree(current!.right)
}
}
}
}
export { TreeNode, BinaryTree }