-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTree.js
More file actions
executable file
·86 lines (64 loc) · 1.71 KB
/
Tree.js
File metadata and controls
executable file
·86 lines (64 loc) · 1.71 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
//import TreeNode from "./TreeNode";
class Tree {
constructor() {
this.root = null;
}
insert(value) {
let node;
if (this.root == null) {
node = this.root = new TreeNode(value);
} else {
node = this.root.insert(value);
}
console.log("-");
printTitle("Insert " + value)
paintTree(this);
return node;
}
remove(value) {
if (this.root != null) {
this.root.remove(value);
if (this.root.value == undefined) {
this.root = null;
}
}
printTitle("Delete " + value)
paintTree(this);
}
traversePreOrder() {
if (this.root)
return this.root.traverse(Traverse.PreOrder);
return [];
}
traverseInOrder() {
if (this.root)
return this.root.traverse(Traverse.InOrder);
return [];
}
traversePostOrder() {
if (this.root)
return this.root.traverse(Traverse.PostOrder);
return [];
}
array() {
if (this.root == null) return [];
let rtn = [];
/**
* make array
* @param {number} p parent index
* @param {number} d 1 = left, 2 = right
* @param {TreeNode} target the target tree node
*/
function make(p, d, target) {
if (target == null) return;
let this_p = 2 * p + d;
rtn[this_p] = target.value;
make(this_p, 1, target.left);
make(this_p, 2, target.right);
}
rtn[0] = this.root.value;
make(0, 1, this.root.left);
make(0, 2, this.root.right);
return rtn;
}
}