0

Didn't find a suitable title, forgive me for that, anyways

Im trying to analyze a recursion function of BST, which returns 1.

After my bad calculations, I got return value of 0, I want to understand what am I doing here wrong.

We call the function like that from main.c: func_3(root, 9);

So sum = 9

Here's the block of code:

int func_3(struct node* node, int sum)
 {
        if (node == NULL) 
              return(sum == 0);
        else 
        {
            int subSum = sum - node->data;
            return (func_3(node->left, subSum) ||  func_3(node->right, subSum));

         }
 }

Here's the BST: enter image description here

My calculations: func(5,9) -> func3(3,4) -> func(1,1) -> returns subTree = sum = 0.

Tilak Madichetti
  • 4,110
  • 5
  • 34
  • 52
Ilan Aizelman WS
  • 1,630
  • 2
  • 21
  • 44

1 Answers1

1

This function returns 1 if there is a path (root node to a leaf node) whose sum of values is equal to sum.

In your function call func_3(root, 9) in main, what you are trying to do is check if there is any path in your binary tree, such that the sum of values of all the nodes in that path is equal to 9.

There is such path, which is the leftmost path (5->3->1), so your function will return 1.

This is how it is returning 1. First call is

func_3(node, 9)

where node is pointing to root node of this tree, i.e. root node with value 5.

Here node is not null. So,

subSum = 9 - 5 = 4.

Next call is

func3(node, 4)

where node is pointing to node with value 3 (left child of node of previous call)

Here again node is not null, So,

subSum = 4 - 3 = 1

Next call is

func3(node, 1)

where node is pointing to node with value 1 (left child of node of previous call)

Here again node is not null, So,

subSum = 1 - 1 = 0

Next call is

func_3(node, 0)

where node is pointing to NULL (left child of node of previous call)

However this time node is NULL, and since sum == 0 is true, it will return 1, And this return value is returned all the way up the recursion and finally to main.

sps
  • 2,720
  • 2
  • 19
  • 38
  • Thank you very much sps! – Ilan Aizelman WS Jul 06 '16 at 15:26
  • 1
    wc. Also, one more thing to note. The reasoning you gave at the end of your question (for return value being 0) shows that you are confused about when this function can return 0. For this funciton to return 0, it should traverse `each and every` path. That is because you have `return func_3(node->left, subSum) || func_3(node->right, subSum)`, so you can see, if `1` is not returned from `func_3(node->left, subSum)`, then `func_3(node->right, subSum)` is called. So you see that for a `0` to be returned `every` path is traversed. – sps Jul 06 '16 at 15:32
  • Excellent explanation! I understand it even better now. Thank you `sps` ! – Ilan Aizelman WS Jul 06 '16 at 15:34