-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtree.js
47 lines (45 loc) · 1.55 KB
/
tree.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
function BinarySearchTree() {
var Node = function(key){
this.key = key;
this.left = null;
this.right = null;
};
var root = null; }
this.insert = function(key){
var newNode = new Node(key);
if (root === null){
root = newNode;
} else {
insertNode(root,newNode);}
};
var insertNode = function(node, newNode){
if (newNode.key < node.key){
if (node.left === null){
node.left = newNode;
} else {
insertNode(node.left, newNode); }
} else {
if (node.right === null){
node.right = newNode;
} else {insertNode(node.right, newNode);
}
}
};
var tree = new BinarySearchTree();
tree.insert(11);
tree.insert(7);
tree.insert(15);
tree.insert(5);
tree.insert(3);
this.inOrderTraverse = function(callback){
inOrderTraverseNode(root, callback);}
var inOrderTraverseNode = function (node, callback)
{
if (node !== null) {
inOrderTraverseNode(node.left, callback);
callback(node.key);
inOrderTraverseNode(node.right, callback);
} };
function printNode(value){
console.log(value); }
tree.inOrderTraverse(printNode);