11package com .thealgorithms .backtracking ;
2- import java .util .*;
2+
3+ import java .util .ArrayList ;
4+ import java .util .List ;
5+
36public class BinaryTreePaths {
4- static class TreeNode {
7+
8+ public static class TreeNode {
59 int val ;
610 TreeNode left ;
711 TreeNode right ;
@@ -10,18 +14,26 @@ static class TreeNode {
1014 this .val = val ;
1115 }
1216 }
17+
1318 public List <String > binaryTreePaths (TreeNode root ) {
1419 List <String > list = new ArrayList <>();
15- if (root == null ) return list ;
20+ if (root == null ) {
21+ return list ;
22+ }
1623 dfs (root , "" , list );
1724 return list ;
1825 }
1926
2027 private void dfs (TreeNode node , String path , List <String > list ) {
21- if (node == null ) return ;
28+ if (node == null ) {
29+ return ;
30+ }
2231
23- if (path .isEmpty ()) path = "" + node .val ;
24- else path += "->" + node .val ;
32+ if (path .isEmpty ()) {
33+ path = Integer .toString (node .val );
34+ } else {
35+ path += "->" + node .val ;
36+ }
2537
2638 if (node .left == null && node .right == null ) {
2739 list .add (path );
@@ -31,45 +43,4 @@ private void dfs(TreeNode node, String path, List<String> list) {
3143 dfs (node .left , path , list );
3244 dfs (node .right , path , list );
3345 }
34- private static TreeNode buildTreeFromInput (Scanner sc ) {
35- System .out .print ("Enter number of nodes: " );
36- int n = sc .nextInt ();
37- if (n == 0 ) return null ;
38-
39- System .out .println ("Enter node values in level order (use -1 for nulls):" );
40- int [] values = new int [n ];
41- for (int i = 0 ; i < n ; i ++) values [i ] = sc .nextInt ();
42-
43- if (values [0 ] == -1 ) return null ;
44- TreeNode root = new TreeNode (values [0 ]);
45- Queue <TreeNode > queue = new LinkedList <>();
46- queue .add (root );
47-
48- int i = 1 ;
49- while (i < n && !queue .isEmpty ()) {
50- TreeNode current = queue .poll ();
51- if (i < n && values [i ] != -1 ) {
52- current .left = new TreeNode (values [i ]);
53- queue .add (current .left );
54- }
55- i ++;
56- if (i < n && values [i ] != -1 ) {
57- current .right = new TreeNode (values [i ]);
58- queue .add (current .right );
59- }
60- i ++;
61- }
62- return root ;
63- }
64-
65- public static void main (String [] args ) {
66- Scanner sc = new Scanner (System .in );
67- TreeNode root = buildTreeFromInput (sc );
68-
69- BinaryTreePaths solver = new BinaryTreePaths ();
70- List <String > result = solver .binaryTreePaths (root );
71-
72- System .out .println ("All root-to-leaf paths: " + result );
73- sc .close ();
74- }
7546}
0 commit comments