-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathttbfspreorder.js
112 lines (90 loc) · 2.41 KB
/
ttbfspreorder.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
class Node{
constructor(val){
this.val = val;
this.left = null;
this.right = null;
}
}
class BST{
constructor(){
this.root = null;
}
insert(val){
val = new Node(val);
if(!this.root){
this.root = val;
return this;
}
let parent = this.root;
let setParent = () => {
if(val.val<parent.val && !parent.left) {parent.left = val; return;}
if(val.val>=parent.val && !parent.right) {parent.right = val; return;}
parent = val.val<parent.val? parent.left : parent.right;
return setParent();
}
setParent();
return this;
}
find(el){
if(!this.root) return !!null;
if(el === this.root.val) return this.root;
let cur = this.root;
let getElement = () => {
if(cur === null) return cur = null;
if(el === cur.val) return cur;
if(el<cur.val) cur = cur.left;
if(el>cur.val) cur = cur.right;
return getElement();
}
getElement();
return !!cur, cur;
}
bfs(){
if(!this.root) return false;
let result =[this.root.val];
let que = [];
let helper = (start = this.root) =>{
if(start.left) {que.unshift(start.left);}
if(start.right) {que.unshift(start.right);}
if(que.length === 0) return result;
start = que.pop();
console.log('que pop',start.val);
// if(start.right && start.left) que.push(start.left.val,start.right.val);
result.push(start.val) //!start.right && //!start.left &&
// console.log('this is the que:',result,'and this is the start:',(start)? start.val : null);
return result.concat(helper(start));
}
helper();
return result;
}
dfsPO(start = this.root){
if(!this.root) return false;
let result =[this.root.val];
if(start !== this.root){
result = [];
}
if(!start) return result;
if(start.left) {result.push(start.left.val);}
if(start.right) {result.push(start.right.val);}
// if(start.right && start.left) que.push(start.left.val,start.right.val);
//!start.right && //!start.left &&
// console.log('this is the que:',result,'and this is the start:',(start)? start.val : null);
return result.concat(this.dfsPO(start.left)).concat(this.dfsPO(start.right));
}
}
let mapple = new BST();
mapple.insert(5);
mapple.insert(7);
mapple.insert(8);
mapple.insert(3);
mapple.insert(2);
mapple.insert(1);
mapple.insert(19);
mapple.insert(20);
mapple.insert(4);
mapple.insert(6);
mapple.insert(9);
console.log(mapple);
console.log(mapple.root.left);
console.log(mapple.root.right);
console.log(mapple.dfsPO());