Amazon Interview Question
Software Engineer / Developersbool isPathExists(Node *root, int N)
{
return tree(root, 0, N);
}
bool tree(Node *root , int sum, int N)
{
if ( root->left == NULL && root->right ==NULL)
{
if ((sum+root->value) == N)
return true;
else
return false;
}
sum = sum + root->value;
if (tree(root->left, sum, N) == true)
return true;
else if (tree(root->right, sum, N) == true)
return true;
else
return false;
}
Does the path have to necessarily start at the root node and end at a leaf? In your original example, what if the desired sum was was 9, and there are connected nodes (3, 6) that sum to to that but neither starts at the root.
Also, a path could comprise of just a single node. Is the desired sum was 7, there are three paths that sum up to this value - (1, 2, 4), (2, 5), and (7).
public static boolean isPathExists(Node curr_node, int sum, int N)
{
if(curr_node == null)
{
if(sum == N)
{
return true;
}
else
{
return false;
}
}
else
{
sum = sum + curr_node.value;
if(isPathExists(curr_node.left,sum,N))
return true;
else if(isPathExists(curr_node.right,sum,N))
return true;
else
return false;
}
}
call it like this
isPathExists(myBinaryTree.root, 0, path_value);
<pre lang="c++" line="1" title="CodeMonkey23490" class="run-this">bool isPathExists(Node *root,int N)
- Anonymous May 26, 2010{
if(root==NULL)
return(N==0);
else
return isPathExists(root->left,N-root->data)||isPathExists(root->right,N-root->data);
}</pre><pre title="CodeMonkey23490" input="yes">1
2
10
42
11
</pre>