Max depth of Binary search tree

Deadly 提交于 2019-12-11 19:04:45

问题


I want to find the max depth of binary search tree. I found a code.

int maxDepth(struct node* node) { 
  if (node==NULL) { 
    return(0); 
  } 
  else { 
    // compute the depth of each subtree 
    int lDepth = maxDepth(node->left); 
    int rDepth = maxDepth(node->right);
    // use the larger one 
    if (lDepth > rDepth) return(lDepth+1); 
    else return(rDepth+1); 
  } 
} 

I want to know that how come node->left would return 1 ?

Is it by default ? The code is easy but I do not know from where is the answer coming, can anyone explain me please ?


回答1:


Given this tree:

[A]

/ \

[B] [C]

maxDepth will be called for [B] with NULL, and for [C] with NULL, both return zero and so the recursive call ends up returning 0+1.

If you had a node [D] under [C] then the call to [D] maxDepth will return NULL and D will return 0+1, then the recursion will keep scaling up and [C] will receive 0+1 and will some +1, returning a maxDepth of 2 which is bigger than the depth of the branch that holds [B] which is 1 so maxDepth of 2 is returned from the complete recursion.




回答2:


When node points to a leaf, both its node->left and node->right is NULL. So maxDepth() both return 0. So the current recursion for this leaf just returns with depth 0 + 1 = 1.

You can prove its correctness.

Initialization

When the node is NULL, it returns 0. And it's true that an empty tree has depth 0. When the node is leaf, it returns 1. As just explained.

Maintenance

If a node exists(not NULL) and we know the depths of its children, the depth of this node will be the max(depth of left, depth of right) + 1. And that's what returned.

Termination

It will terminate because when it reaches the leaf, the recursion will stop getting deeper and return. When the whole recursion finishes, maxDepth(root) returns the depth of the root.



来源:https://stackoverflow.com/questions/23146843/max-depth-of-binary-search-tree

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