-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTree-function.js
More file actions
79 lines (65 loc) · 1.65 KB
/
BinaryTree-function.js
File metadata and controls
79 lines (65 loc) · 1.65 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
function Node(data) {
this.data = data
this.left = null
this.right = null
}
Node.prototype.addNode = function(node) {
if(node.data < this.data) {
if(this.left === null) {
this.left = node
}else {
this.left.addNode(node)
}
}else if(node.data > this.data) {
if(this.right === null) {
this.right = node
}else {
this.right.addNode(node)
}
}else {
console.log('try different number')
}
}
Node.prototype.visit = function() {
console.log(this.data)
if(this.left !== null) {
this.left.visit()
}
if(this.right !== null) {
this.right.visit()
}
}
Node.prototype.search = function(data) {
if(this.data === data) {
return this
}else if(data < this.data && this.left !== null) {
return this.left.search(data)
}else if(data > this.data && this.right !== null) {
return this.right.search(data)
}
return null
}
-------------------------------------------------------------------------------------------------------------------------
function BinaryTree() {
this.root = null
}
BinaryTree.prototype.insert = function(data) {
var node = new Node(data)
if(this.root === null) {
this.root = node
}else {
this.root.addNode(node)
}
}
BinaryTree.prototype.traverse = function() {
this.root.visit()
}
BinaryTree.prototype.search = function(data) {
var node = this.root.search(data)
return node
}
var bt = new BinaryTree()
var nodes = [3,5,6,7]
nodes.forEach(node => bt.addValue(node))
console.log(bt, bt.traverse())
console.log(bt.search(5))