The following is an interview question.
You are given a binary tree (not necessarily BST) in which each node contains a value. Design an algorithm t
I have improved some coding logic of answer by Arvind Upadhyay. Once the if loop done, you can not use the same list. So need to create the new list. Also, there is need to maintain count of level the logic go down for from current node to search path. If we do not find path, so before going to its children, we need to come out from the recursive call equal to count times.
int count =0;
public void printAllPathWithSum(Node node, int sum, ArrayList list)
{
if(node == null)
return;
if(node.data<=sum)
{
list.add(node.data);
if(node.data == sum)
print(list);
else
{
count ++;
printAllPathWithSum(node.left, sum-node.data, list);
printAllPathWithSum(node.right, sum-node.data, list);
count --;
}
}
if(count != 0)
return ;
printAllPathWithSum(node.left, this.sum, new ArrayList());
if(count != 0)
return;
printAllPathWithSum(node.right, this.sum, new ArrayList());
}
public void print(List list)
{
System.out.println("Next path");
for(int i=0; i
Check the full code at: https://github.com/ganeshzilpe/java/blob/master/Tree/BinarySearchTree.java