-
Notifications
You must be signed in to change notification settings - Fork 0
/
bstTraversal.js
81 lines (70 loc) · 1.53 KB
/
bstTraversal.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
class node{
constructor(value){
this.value=value
this.left=null
this.right=null
}
}
class binaryTree{
constructor(){
this.root=null
}
getroot(){
return this.root
}
insert(value){
let newNode=new node(value)
if(this.root==null){
this.root=newNode
}else{
this.insertNode(this.root,newNode)
}
}
insertNode(root,newNode){
if(newNode.value< root.value){
if(root.left==null){
root.left=newNode
}else{
this.insertNode(root.left,newNode)
}
}else{
if(root.right==null){
root.right=newNode
}else{
this.insertNode(root.right,newNode)
}
}
}
inorder(root){
if(root!=null){
this.inorder(root.left)
console.log(root.value)
this.inorder(root.right)
}
}
preorder(root){
if(root!=null){
console.log(root.value)
this.preorder(root.left)
this.preorder(root.right)
}
}
postorder(root){
if(root!=null){
this.postorder(root.left)
this.postorder(root.right)
console.log(root.value)
}
}
}
let bt=new binaryTree
bt.insert(34)
bt.insert(58)
bt.insert(23)
let root=bt.getroot()
console.log("inorder");
bt.inorder(root)
console.log("preorder");
bt.preorder(root)
console.log("postorder");
bt.postorder(root)