-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinaryTree.js
More file actions
53 lines (45 loc) · 1.33 KB
/
Copy pathbinaryTree.js
File metadata and controls
53 lines (45 loc) · 1.33 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
class binaryTree {
constructor(value, left=null, right=null) {
this.value = value;
this.left = left;
this.right = right;
}
getNumNodes() {
if(this == null) {
return 0
}
else {
return 1 + (this.left != null ? this.left.getNumNodes() : 0) + (this.right != null ? this.right.getNumNodes() : 0);
}
}
static generateBinaryTree(numNodes){
let initialNode = new binaryTree(getRndInteger(-10, 10))
for(let i = 1; i < numNodes; i++) {
this.populateDown(initialNode, new binaryTree(getRndInteger(-10, 10)));
}
return initialNode;
}
static populateDown(parent, node) {
if (getRndInteger(0,1) == 0) {
if (parent.left == null) {
parent.left = node;
}
else {
this.populateDown(parent.left, node);
}
}
else {
if (parent.right == null) {
parent.right = node;
}
else {
this.populateDown(parent.right, node);
}
}
}
}
// inclusive on both sides
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min + 1) ) + min;
}
console.log(binaryTree.generateBinaryTree(getRndInteger(1, 10)).getNumNodes());