0
\$\begingroup\$

For a given binary tree and a sum, I have written the following function to check whether there is a root to leaf path in that tree with the given sum.

/* 
//A binary tree node
struct Node
{
 int data;
 struct Node* left, * right;
}; 
*/
bool hasPathSum(Node *node, int sum)
{
 if(!node)
 return sum==0;
 return ( hasPathSum(node->left, sum-node->data) || 
 hasPathSum(node->right, sum-node->data) );
}

Are there any edge cases in which the code will break? Also, do comment on the code style.

asked Oct 7, 2016 at 0:45
\$\endgroup\$
3
  • \$\begingroup\$ @JerryCoffin: The sum==0 statement is reached only when node==NULL. Otherwise hasPathSum is recursively called on left and right subtree until it reaches left or right subtree of a leaf node. \$\endgroup\$ Commented Oct 7, 2016 at 4:23
  • \$\begingroup\$ It seems fine to me. \$\endgroup\$ Commented Oct 7, 2016 at 4:29
  • \$\begingroup\$ Oops--I misread. My apologies. \$\endgroup\$ Commented Oct 7, 2016 at 4:55

1 Answer 1

1
\$\begingroup\$
  • Give your operators some breathing space.

     if (!node) {
     return sum == 0;
     }
     return hasPathSum(node->left, sum - node->data) || 
     hasPathSum(node->right, sum - node->data);
    

    Note that return expression needs no parenthesis.

  • sum - node->data seems more natural to be expressed once:

     sum -= node->data;
     return hasPathSum(node->left, sum) || 
     hasPathSum(node->right, sum);
    
  • I see no edge cases except possible overflows.

answered Oct 7, 2016 at 8:21
\$\endgroup\$
2
  • \$\begingroup\$ Thanks, henceforth I will see to it that operators get space to breathe. I see in your code you have omitted the parenthesis in return statement and added braces for if construct. Will you suggest me how do I decide whether to use/omit braces in the code(of course in cases where it is not necessary to use them), whether I should use/omit the parenthesis(again when they are not necessary to be used)? \$\endgroup\$ Commented Oct 8, 2016 at 1:00
  • \$\begingroup\$ @shridharfly It is generally recommended to never omit braces. Parenthesis OTOH are less strict. Use them to emphasize the priority of subexpressions. Parenthesis around an entire expression are never used; particularly with return expression. \$\endgroup\$ Commented Oct 8, 2016 at 3:15

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.