File tree 1 file changed +16
-15
lines changed
1 file changed +16
-15
lines changed Original file line number Diff line number Diff line change 14
14
* @return {string }
15
15
*/
16
16
var tree2str = function ( root ) {
17
+ return dfs ( root , [ ] ) . join ( "" ) ;
18
+ } ;
17
19
18
- let str = "" ;
19
- const dfs = ( node ) => {
20
- if ( ! node ) return ;
21
- str += node . val ;
22
- if ( node . right || node . left ) str += "(" ;
23
- dfs ( node . left ) ;
24
- if ( node . right || node . left ) str += ")" ;
20
+ const dfs = ( node , strArr ) => {
21
+ if ( ! node ) return ;
25
22
26
- // right tree
27
- if ( node . right ) str += "(" ;
28
- dfs ( node . right ) ;
29
- if ( node . right ) str += ")" ;
30
- }
23
+ strArr . push ( node . val ) ;
31
24
32
- dfs ( root ) ;
33
- return str ;
34
- } ;
25
+ if ( node . right || node . left ) strArr . push ( "(" ) ;
26
+ dfs ( node . left , strArr ) ;
27
+ if ( node . right || node . left ) strArr . push ( ")" ) ;
28
+
29
+ // right tree
30
+ if ( node . right ) strArr . push ( "(" ) ;
31
+ dfs ( node . right , strArr ) ;
32
+ if ( node . right ) strArr . push ( ")" ) ;
33
+
34
+ return strArr ;
35
+ }
You can’t perform that action at this time.
0 commit comments