Question

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 ?

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top