Friday, September 13, 2013

print all distinct paths form root to all leaf of BST


    public void printAllPaths() {
        int[] arr = new int[100];
        int pathSum = -1;
        printAllPaths(arr, root, pathSum);
    }

    private void printAllPaths(int[] arr, Node node, int pathSum) {
        arr[++pathSum] = node.data;
        if (node.leftChild == null && node.rightChild == null) {
            printPath(arr, pathSum);
        }
        if (node.leftChild != null) {
            printAllPaths(arr, node.leftChild, pathSum);
        }
        if (node.rightChild != null) {
            printAllPaths(arr, node.rightChild, pathSum);
        }
    }

    private void printPath(int[] arr, int pathSum) {
        int data = 0;
        System.out.println();
        for (; data <= pathSum; data++) {
            System.out.print(arr[data] + " , ");
        }
    }

No comments:

Post a Comment