Skip to content

Commit 2b87448

Browse files
author
Tymoteusz
authored
Merge pull request #9 from 403-html/Bug-with-binary-tree-test
Fixed binary tree
2 parents 0b9d86e + 6c9fe8f commit 2b87448

1 file changed

Lines changed: 33 additions & 27 deletions

File tree

binary-tree/tree.js

Lines changed: 33 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,41 @@
1-
class Node {
2-
constructor(val, index) {
3-
this.number = val || null;
4-
this.left = null;
5-
this.right = null;
6-
this.index = index || null;
1+
class Tree {
2+
constructor() {}
3+
addValue(value) {
4+
if (!this.number) {
5+
this.number = value
6+
this.nodeIndex = 0
7+
} else {
8+
if (this.valueIndex) this.valueIndex += 1
9+
else this.valueIndex = 1
10+
// right, higher
11+
if (value > this.number) {
12+
if (this.right) this.right.addValue(value, this.valueIndex)
13+
if (!this.right) this.right = new Branch(value, this.valueIndex)
14+
}
15+
// left, lower
16+
if (value < this.number) {
17+
if (this.left) this.left.addValue(value, this.valueIndex)
18+
if (!this.left) this.left = new Branch(value, this.valueIndex)
19+
}
20+
}
721
}
822
}
923

10-
class Tree {
11-
constructor() {
12-
this.tree = new Node();
24+
class Branch {
25+
constructor(value, index) {
26+
this.number = value
27+
this.nodeIndex = index
1328
}
14-
addValue({value,index}) {
15-
if(index == 0){
16-
this.tree.index = index;
17-
this.tree.number = value;
29+
addValue(value, index) {
30+
// right, higher
31+
if (value > this.number) {
32+
if (!this.right) this.right = new Branch(value, index)
33+
if (this.right) this.right.addValue(value, index)
1834
}
19-
else {
20-
if(value < this.tree.number) this.tree.left = new Node(value,index);
21-
if(value > this.tree.number) this.tree.right = new Node(value,index);
35+
// left, lower
36+
if (value < this.number) {
37+
if (!this.left) this.left = new Branch(value, index)
38+
if (this.left) this.left.addValue(value, index)
2239
}
2340
}
2441
}
25-
26-
let tree = new Tree();
27-
28-
for(let i = 0; i<15; i++){
29-
tree.addValue({
30-
"value": Math.floor(Math.random()*101),
31-
"index": i
32-
});
33-
}
34-
35-
console.log(tree.tree);

0 commit comments

Comments
 (0)