finding depth of a tree?

拈花ヽ惹草 提交于 2020-01-04 04:55:45

问题


I am very new to binary tree and recursion. My program is to find the height of the tree but I am a bit confused as to why my program doesn't work.

struct Node {
    int value;
    Node *left;
    Node *right;
}

int heightOfTree(Node node){
    if(node ==NULL)
    {
         return 0;
    }
    else
    {
       int lheight=heightOfTree(node->left);
       int rheight = heightOfTree(node->right);
       if(lheight>rheight)
       {
           return lheight;
       }
       else
       {
           return rheight;
       }
    }
}

I followed a pseudocode online so I implemented it myself because I don't want to just copy and paste. I tried to insert a lot of nodes but When I run my program I always get 0 height? Thank you


回答1:


return lheight + 1;

and

return rheight + 1;

You need to increment the height at each level.



来源:https://stackoverflow.com/questions/42463585/finding-depth-of-a-tree

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!