-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrees.html
More file actions
117 lines (100 loc) · 3 KB
/
Trees.html
File metadata and controls
117 lines (100 loc) · 3 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
class Node{
constructor(value){
this.value = value;
this.left = null;
this.right = null;
}
}
class BinaryTree{
constructor(){
this.root = null;
}
insert(value){
const newNode = new Node(value);
if(this.root === null){
this.root = newNode;
}
else{
this.insertNode(this.root, newNode)
}
}
insertNode(node,newNode){
if(newNode.value < node.value){
if(node.left === null){
node.left = newNode
}
else{
this.insertNode(node.left,newNode)
}
}else{
if(node.right === null){
node.right = newNode;
}
else{
this.insertNode(node.right,newNode);
}
}
}
inorder(node = this.root){
if(node !== null){
this.inorder(node.left)
console.log(node.value)
this.inorder(node.right)
}
}
preorder(node = this.root){
if(node !== null){
console.log(node.value);
this.preorder(node.left);
this.preorder(node.right);
}
}
postorder(node = this.root){
if(node !== null){
this.postorder(node.left)
this.postorder(node.right)
console.log(node.value)
}
}
search(node,value){
if(node === null){
return null;
}
if(value< node.value){
return this.search(node.left,value)
}
else if(value > node.value){
return this.search(node.right,value)
}
else{
return node;
}
}
}
let tree = new BinaryTree();
tree.insert(10)
tree.insert(5)
tree.insert(15)
tree.insert(3)
tree.insert(25)
console.log("InOrder")
tree.inorder();
console.log("PreOrder")
tree.preorder();
console.log("Postorder")
tree.postorder();
console.log("Search for value: 25")
const result = tree.search(tree.root,35)
console.log(result ? `Found ${result.value}` : "Not Found")
</script>
</body>
</html>