public static void printAllPaths(Node root, int[] arr, int level, int k) { if (root == null) return; findPath(root, k, level, 0, arr, level); printAllPaths(root.left, arr, level + 1, k); printAllPaths(root.right, arr, level + 1, k); } private static void findPath(Node root, int k, int level, int sum, int[] arr, int start) { if (root == null) return; sum += root.val; arr[level] = root.val; if (sum == k) { printPath(arr, start, level); } findPath(root.left, k, level + 1, sum, arr, start); findPath(root.right, k, level + 1, sum, arr, start); } private static void printPath(int[] arr, int start, int end) { for (int i = start; i <= end; i++) { System.out.print(arr[i] + "->"); } System.out.println(); }
public static void printAllPaths(Node root, int[] arr, int level, int k) {
ReplyDeleteif (root == null)
return;
findPath(root, k, level, 0, arr, level);
printAllPaths(root.left, arr, level + 1, k);
printAllPaths(root.right, arr, level + 1, k);
}
private static void findPath(Node root, int k, int level, int sum,
int[] arr, int start) {
if (root == null)
return;
sum += root.val;
arr[level] = root.val;
if (sum == k) {
printPath(arr, start, level);
}
findPath(root.left, k, level + 1, sum, arr, start);
findPath(root.right, k, level + 1, sum, arr, start);
}
private static void printPath(int[] arr, int start, int end) {
for (int i = start; i <= end; i++) {
System.out.print(arr[i] + "->");
}
System.out.println();
}