File tree Expand file tree Collapse file tree 1 file changed +10
-8
lines changed Expand file tree Collapse file tree 1 file changed +10
-8
lines changed Original file line number Diff line number Diff line change @@ -17,21 +17,23 @@ class Solution {
17
17
public List <String > binaryTreePaths (TreeNode root ) {
18
18
19
19
List <String > list = new ArrayList <>();
20
- dfs (root , "" , list );
20
+ StringBuilder sb = new StringBuilder ();
21
+ dfs (root , sb , list );
21
22
return list ;
22
23
}
23
- void dfs (TreeNode node , String path , List <String > list ){
24
+ void dfs (TreeNode node , StringBuilder sb , List <String > list ){
24
25
25
26
if (node ==null )return ;
27
+ int len =sb .length ();
26
28
27
- path += node .val ;
29
+ sb . append ( node .val ) ;
28
30
29
31
if (node .left ==null && node .right ==null ){
30
- list .add (path );
31
- }else {
32
- path +="->" ;
33
- dfs (node .left , path , list );
34
- dfs (node .right , path , list );
32
+ list .add (sb .toString ());
35
33
}
34
+ sb .append ("->" );
35
+ dfs (node .left , sb , list );
36
+ dfs (node .right , sb , list );
37
+ sb .setLength (len );
36
38
}
37
39
}
You can’t perform that action at this time.
0 commit comments