Sachin Godara
Sachin Godara

Reputation: 502

Recursion in Binary Tree

I was trying to solve a problem in tree,And stuck in recursion and write a code. But i cant't figure out that why it's giving this out ! someone help how to code gives this output My program is x=0,y=0

int height1(node *root,int x,int y)

{ 

 int val;

    if(root==NULL)
    return 1;
    else
    {
        x=x+height1(root->left,x,y);
        y=y+height1(root->right,x,y);
        printf("x=%d and y=%d %d\n",x,y,root->data);
        if(x>y)
            return x;
            else
                return y;
    }

it's just a rough work to understand flow of recursion. Input of tree traversing is 50 40 70 45 30 44 48 and value of

       x  y  root->data 
      1   1    30 
      2   1    44
      4   1    48
      3    4    45
      1    4    40
      5     1    70
      4    5     50

why it going out in this way ,in my way it should add y and x each time so value should increase,

Please give me some advise ,because every time i solve a tree problem i always stuck in recursion, can anyone suggest what is right approach.

I understand that to figure out base condition is important, and i know it how to find.But can't get how the output came.

I know that here are many most experienced programmers and i want that please give me some advice because i think they also faced some problems in recursion ,so how they solve this.How they solve recursive problem when any new one come.

Should i refer some book or should i just solve some programs. So Please i want your advise so i can become good in this.

Upvotes: 0

Views: 109

Answers (1)

user4668606
user4668606

Reputation:

This code has a rather strange architecture in general. You could leave the two int arguments away, they are useless. Next problem: this code doesn't count any nodes except for leaves. And this code has some logical mistakes aswell (example: if(root == NULL) return 1; would lead to counting nodes that don't even exist). In general this could be implemented a lot simpler:

int height1(node *root){
    if(root == NULL)
        return 0;

    int l = height1(root->left);
    int r = height1(root->right);

    return (l < r ? r : l) + 1;
}

Upvotes: 1

Related Questions