Friday, September 13, 2013

find the path from root to leaf having sum of all node data equal to given number


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

    private void hasPathSum(int[] arr, Node node, int pathSum, int num) {
        if (node == null) {
            return;
        }
        arr[++pathSum] = node.data;
        num -= node.data;
        if (num == 0 && (node.leftChild == null && node.rightChild == null)) {
            System.out.print("\n has path sum");
            printPath(arr, pathSum);
        }
        if (node.leftChild != null && num >= node.leftChild.data) {
            hasPathSum(arr, node.leftChild, pathSum, num);
        }
        if (node.rightChild != null && num >= node.rightChild.data) {
            hasPathSum(arr, node.rightChild, pathSum, num);
        }
    }

No comments:

Post a Comment