File tree Expand file tree Collapse file tree 1 file changed +68
-0
lines changed Expand file tree Collapse file tree 1 file changed +68
-0
lines changed Original file line number Diff line number Diff line change 1+ //Implement Binary Search tree in Javascript using Classes (ES6)
2+
3+
4+
5+ function Node ( data , left , right ) {
6+ this . data = data ;
7+ this . left = left ;
8+ this . right = right ;
9+ }
10+
11+ const trace = ( curr ) => {
12+ if ( curr . left !== null ) {
13+ trace ( curr . left ) ;
14+ }
15+ if ( curr . right !== null ) {
16+ trace ( curr . right ) ;
17+ }
18+ }
19+
20+ const append = ( curr , data ) => {
21+ if ( data <= curr . data ) {
22+ if ( curr . left === null ) {
23+ curr . left = new Node ( data , null , null ) ;
24+ } else {
25+ append ( curr . left , data ) ;
26+ }
27+ } else {
28+ if ( curr . right === null ) {
29+ curr . right = new Node ( data , null , null ) ;
30+ } else {
31+ append ( curr . right , data ) ;
32+ }
33+ }
34+ }
35+
36+ class BinaryTree {
37+ constructor ( ) {
38+ this . root = new Node ( null , null , null ) ;
39+ }
40+
41+ append ( data ) {
42+ if ( this . root . data === null ) {
43+ this . root = new Node ( data , null , null ) ;
44+ } else {
45+ const curr = this . root ;
46+ append ( curr , data ) ;
47+ }
48+ }
49+
50+ trace ( ) {
51+ if ( this . root . data === null ) {
52+ return this . root . data ;
53+ } else {
54+ const curr = this . root ;
55+ trace ( curr ) ;
56+ }
57+ }
58+ }
59+
60+
61+ const tree = new BinaryTree ( ) ;
62+ tree . append ( 10 ) ;
63+ tree . append ( 5 ) ;
64+ tree . append ( 20 ) ;
65+ tree . append ( 6 ) ;
66+ tree . append ( 15 ) ;
67+ tree . trace ( ) ;
68+ console . log ( tree ) ;
You can’t perform that action at this time.
0 commit comments