Wednesday, August 20, 2014

Print all paths with given sum in binary tree - Java


Program:

Call Method:

int[] arr = new int[heightTree(root)];

printAllPaths(root, arr, 0, sum);




Better approach:




1 comment:

  1. 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();
    }

    ReplyDelete