File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed
Data-Structure/Tree/Binary Search Tree/Construction and Conversion Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change 1+ 'use strict' ;
2+ class Node {
3+ constructor ( data ) {
4+ this . data = data ;
5+ this . leftNode = this . rightNode = null ;
6+ }
7+ }
8+
9+ function constructTrees ( start , end ) {
10+ let list = [ ] ;
11+ if ( start > end ) {
12+ list . push ( null ) ;
13+ return list ;
14+ }
15+ for ( let i = start ; i <= end ; i ++ ) {
16+ let leftList = constructTrees ( start , i - 1 ) ;
17+ let rightList = constructTrees ( i + 1 , end ) ;
18+ for ( let j = 0 ; j < leftList . length ; j ++ ) {
19+ let leftNode = leftList [ j ] ;
20+ for ( let k = 0 ; k < rightList . length ; k ++ ) {
21+ let rightNode = rightList [ k ] ;
22+ let temp = new Node ( i ) ;
23+ temp . leftNode = leftNode ;
24+ temp . rightNode = rightNode ;
25+ list . push ( temp ) ;
26+ }
27+ }
28+ }
29+ return list ;
30+ }
31+
32+ function preOrderDisplay ( root , preOrderArr ) {
33+ if ( root == null ) return ;
34+ preOrderArr . push ( root . data ) ;
35+ preOrderDisplay ( root . leftNode , preOrderArr ) ;
36+ preOrderDisplay ( root . rightNode , preOrderArr ) ;
37+ }
38+
39+ let BSTTrees = constructTrees ( 1 , 3 ) ;
40+ let preOrderArr = [ ] ;
41+ for ( let index = 0 ; index < BSTTrees . length ; index ++ ) {
42+ preOrderArr = [ ] ;
43+ preOrderDisplay ( BSTTrees [ index ] , preOrderArr ) ;
44+ console . log ( 'preOrder Display - ' , preOrderArr . join ( ' ,' ) ) ;
45+ }
You can’t perform that action at this time.
0 commit comments