Skip to content

Commit 71ce106

Browse files
Add BinaryTreePaths algorithm with user input example
1 parent 329c1d9 commit 71ce106

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
package com.thealgorithms.backtracking;
2+
import java.util.*;
3+
public class BinaryTreePaths {
4+
static class TreeNode {
5+
int val;
6+
TreeNode left;
7+
TreeNode right;
8+
9+
TreeNode(int val) {
10+
this.val = val;
11+
}
12+
}
13+
public List<String> binaryTreePaths(TreeNode root) {
14+
List<String> list = new ArrayList<>();
15+
if (root == null) return list;
16+
dfs(root, "", list);
17+
return list;
18+
}
19+
20+
private void dfs(TreeNode node, String path, List<String> list) {
21+
if (node == null) return;
22+
23+
if (path.isEmpty()) path = "" + node.val;
24+
else path += "->" + node.val;
25+
26+
if (node.left == null && node.right == null) {
27+
list.add(path);
28+
return;
29+
}
30+
31+
dfs(node.left, path, list);
32+
dfs(node.right, path, list);
33+
}
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+
}
75+
}

0 commit comments

Comments
 (0)