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 . branchIndex = 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 . branchIndex = 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}
2542
26- let tree = new Tree ( ) ;
43+ /*
44+ branch (nr, index)
45+ -> inaczej
46+ -> sprawdź czy pasuje do lewego brancha (mniejszy niż numer)
47+ -> nie, to wstaw numerem i indexem
48+ -> tak, to wrzuć nowy branch, który stworzy nowy branch
49+ -> sprawdź czy pasuje do prawego brancha (wiekszy niż numer)
50+ -> nie, to wstaw nowy branch z numerem
51+ -> tak, to wrzuć nowy branch, który stworzy nowy branch
52+ */
2753
28- for ( let i = 0 ; i < 15 ; i ++ ) {
29- tree . addValue ( {
30- "value" : Math . floor ( Math . random ( ) * 101 ) ,
31- "index" : i
32- } ) ;
33- }
54+ // let tree = new Tree()
55+
56+ // for (let i = 0; i < 15; i++) {
57+ // tree.addValue(Math.floor(Math.random() * 101))
58+ // }
3459
35- console . log ( tree . tree ) ;
60+ // console.log(JSON.stringify( tree, null, 2))
0 commit comments