-
Notifications
You must be signed in to change notification settings - Fork 0
/
bstInsert&Traversal.js
88 lines (71 loc) · 1.56 KB
/
bstInsert&Traversal.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
class node{
constructor(value){
this.value=value
this.left=null
this.right=null
}
}
class binaryTree{
constructor(){
this.root=null
}
getroot(){
return this.root
}
insertNode(value){
let newNode=new node(value)
if(this.root==null){
this.root=newNode
}else{
this.insert(this.root,newNode)
}
}
insert(root,newNode){
if(newNode.value<root.value){
if(root.left==null){
root.left=newNode
}else{
this.insert(root.left,newNode)
}
}else{
if(root.right==null){
root.right=newNode
}else{
this.insert(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.insertNode(50)
bt.insertNode(25)
bt.insertNode(65)
let root=bt.getroot()
console.log("inorder")
bt.inorder(root)
console.log("preorder")
bt.preorder(root)
console.log("postorder")
bt.postorder(root)
// console.log(bt);