@@ -2,21 +2,87 @@ import TreeNode from "./data-structures/TreeNode";
22import renderTree from "./render/drawTree" ;
33
44const canvas = document . querySelector ( "canvas" ) ;
5- const root = new TreeNode ( 10 ) ;
6- const root1 = new TreeNode ( 12 ) ;
7- root . setLeftNode ( root1 ) ;
5+ const textArea = document . querySelector ( "textarea" ) ;
6+ const runBtn = document . querySelector ( "#run-btn" ) ;
7+ const clearBtn = document . querySelector ( "#clear-btn" ) ;
88
9- const root2 = new TreeNode ( 13 ) ;
10- root . setRightNode ( root2 ) ;
9+ runBtn ?. addEventListener ( "click" , ( ) => {
1110
11+ if ( textArea ?. value === "" ) return ;
1212
13- const root3 = new TreeNode ( 13 ) ;
14- root2 . setRightNode ( root3 ) ;
15- root1 . setLeftNode ( root3 ) ;
13+ const root = constructTree ( ) ;
1614
15+ renderTree ( root , canvas )
16+ } )
1717
18- const root4 = new TreeNode ( 11 ) ;
19- root2 . setLeftNode ( root4 ) ;
18+ clearBtn ?. addEventListener ( "click" , ( ) => {
19+ ( textArea as HTMLTextAreaElement ) . value = "" ;
20+ const context = canvas ?. getContext ( '2d' ) ;
21+ context ?. clearRect ( 0 , 0 , canvas ! . width , canvas ! . height )
22+ } )
2023
24+ function constructTree ( ) : TreeNode {
2125
22- renderTree ( root , canvas )
26+ let parsedInputArray = parseInput ( textArea ! . value ) ;
27+
28+ const queue :TreeNode [ ] = [ ] ;
29+
30+ let idx = 0 ;
31+ const root = new TreeNode ( parsedInputArray [ idx ] ) ;
32+ idx ++ ;
33+
34+ queue . push ( root ) ;
35+
36+ while ( queue . length > 0 && idx < parsedInputArray . length ) {
37+ const currentNode = queue . shift ( ) ;
38+
39+ // left child
40+ if ( idx < parsedInputArray . length ) {
41+
42+ if ( parsedInputArray [ idx ] != null ) {
43+ const leftNode = new TreeNode ( parsedInputArray [ idx ] ) ;
44+ currentNode ?. setLeftNode ( leftNode ) ;
45+ queue . push ( leftNode ) ;
46+ }
47+ idx ++ ;
48+ }
49+
50+ // right child
51+ if ( idx < parsedInputArray . length ) {
52+
53+ if ( parsedInputArray [ idx ] != null ) {
54+ const rightNode = new TreeNode ( parsedInputArray [ idx ] ) ;
55+ currentNode ?. setRightNode ( rightNode ) ;
56+ queue . push ( rightNode ) ;
57+ }
58+ idx ++ ;
59+ }
60+ }
61+
62+
63+ return root ;
64+ }
65+
66+ function parseInput ( input : string ) {
67+ let parsedInput = "" ;
68+
69+ for ( let i = 0 ; i < input . length ; i ++ ) {
70+ const ch = input . charAt ( i ) ;
71+
72+ if ( ch !== ' ' && ch !== '[' && ch !== ']' ) parsedInput += ch ;
73+ }
74+
75+ return parsedInput . split ( ',' ) . map ( ( ele ) => {
76+ if ( ele === 'null' ) return null ;
77+ return parseInt ( ele ) ;
78+ } )
79+ }
80+
81+ window . addEventListener ( 'resize' , ( ) => {
82+ const context = canvas ?. getContext ( '2d' ) ;
83+ context ?. clearRect ( 0 , 0 , canvas ! . width , canvas ! . height )
84+
85+ const root = constructTree ( ) ;
86+
87+ renderTree ( root , canvas )
88+ } )
0 commit comments