Thursday, June 2, 2011

WAP to print All Path That Sums Up to Given value In Binary Tree

Given a binary tree and a number, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals the given number.

Special Case 1 what happen if got sum=0 in the mid before reaching to leaf nodes.?
Special Case 2 what happens if path not starts from root..?? More Important

Status: Modification Needed

#include
#include
#define bool int

/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct node
{
int data;
struct node* left;
struct node* right;
};

/*
Given a tree and a sum, return true if there is a path from the root
down to a leaf, such that adding up all the values along the path
equals the given sum.

Strategy: subtract the node value from the sum when recurring down,
and check to see if the sum is 0 when you run out of tree.
*/

void printArray(int ints[], int len)
{
int i;
for (i=0; i {
printf("%d ", ints[i]);
}
printf("\n");
}


void hasPathSum(struct node* node, int sum,int ar[],int index)
{

if(node==NULL)//Tree Empty
return;

/* return true if we are not run out of tree and sum==0 */
if(sum==0)
{
printArray(ar,index);//case arrive when we haven't traversed the tree but foun
//the path before reaching the leaf nodes
return;
}


else
{


ar[index]=node->data;
index++;

int subSum = sum - node->data;

/* If we reach a leaf node and sum becomes 0 then return true*/
if (subSum == 0 && node->left == NULL && node->right == NULL )
printArray(ar,index);
if(node->left)
hasPathSum(node->left,subSum,ar,index);
if(node->right)
hasPathSum(node->right, subSum,ar,index);

}
}


void hasPath(struct node* root, int sum)
{
int ar[100];
hasPathSum(root,sum,ar,0);

}

/* UTILITY FUNCTIONS */
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct node* newnode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;

return(node);
}

/* Driver program to test above functions*/
int main()
{

int sum = 20;//21,10; 2nd special case 20 1st special case

/* Constructed binary tree is
10
/ \
8 2
/ \ / \
3 2 9 4
*/
struct node *root = newnode(10);
root->left = newnode(8);
root->right = newnode(2);
root->left->left = newnode(3);
root->left->right = newnode(2);
root->left->right->left = newnode(1);
root->right->left = newnode(9);
root->right->right= newnode(8);
root->right->right->left= newnode(5);
hasPath(root, sum);

getchar();
return 0;
}

TC O(n)
SC O(1)
Run here https://ideone.com/rnkWi
Run here For Negative Numbers https://ideone.com/HNbFo

2 comments :

Anonymous said...

this program doesn't print anything if given sum is not found...

Unknown said...

@Anon , it can be avoided by putting a else condition , think about it ;)