/
binaryTree.js
75 lines (59 loc) · 1.46 KB
/
binaryTree.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
// Define a class Node
function Node(data, left, right) {
this.data = data;
this.left = left;
this.right = right;
};
// Helper function for connecting Nodes to the left
Node.prototype.addLeft = function(node) {
this.left = node;
};
// Helper function for connecting Nodes to the right
Node.prototype.addRight = function(node) {
this.right = node;
};
// Output a Node's data
Node.prototype.log = function(buffer) {
console.log(this.data.toString());
};
// Let's start with adding a bunch of sorted Nodes
// to a Binary Tree
var sortedNodes = [
new Node(1),
new Node(2),
new Node(3),
new Node(4),
new Node(5),
new Node(6),
new Node(7)
];
var binaryTree = sortedNodes[3];
binaryTree.addLeft(sortedNodes[1]);
binaryTree.addRight(sortedNodes[5]);
binaryTree.left.addLeft(sortedNodes[0]);
binaryTree.left.addRight(sortedNodes[2]);
binaryTree.right.addLeft(sortedNodes[4]);
binaryTree.right.addRight(sortedNodes[6]);
// In order traversal of binary tree
var InOrderTraversal = function(node) {
if (node.left) {
InOrderTraversal(node.left);
}
node.log();
if (node.right) {
InOrderTraversal(node.right);
}
};
// Run it
console.log('In order traversal of our Binary Tree:');
InOrderTraversal(binaryTree);
// Height of binary tree
var FindHeight = function(root) {
if (!root) {
return 0;
}
return Math.max(FindHeight(root.left), FindHeight(root.right)) + 1;
};
// Run it
console.log('The height of our Binary Tree is:');
console.log(FindHeight(binaryTree));