二进制搜索树的最大深度

Max depth of Binary search tree

本文关键字:深度 搜索树 二进制      更新时间:2023-10-16

我想找到二进制搜索树的最大深度。我找到了一个代码。

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); 
  } 
} 

我想知道node->left怎么会返回1?

它是默认的吗?代码很简单,但我不知道从哪里来的答案,有人能解释一下吗?

给定此树:

[A]

/\

[B] [C]

对于带有NULL的[B]和带有NULL的[C],将调用maxDepth,两者都返回零,因此递归调用最终返回0+1。

如果在[C]下有一个节点[D],那么对[D]maxDepth的调用将返回NULL,D将返回0+1,然后递归将继续按比例放大,[C]将接收0+1,并返回一些+1,返回的maxDepth为2,它大于持有[B]的分支的深度,即1,因此maxDepth 2从完整递归中返回。

node指向一个叶时,它的node->leftnode->right都是NULL。所以maxDepth()都返回0。因此,该叶的当前递归只返回深度为0 + 1 = 1.

你可以证明它的正确性。

初始化

当节点为NULL时,返回0。的确,一棵空树的深度为0。当节点是叶子时,它返回1。正如刚才所解释的。

维护

如果存在一个节点(不是NULL),并且我们知道其子节点的深度,则该节点的深度将是max(depth of left, depth of right) + 1。这就是回报。

终止

它将终止,因为当它到达叶时,递归将停止变得更深并返回。当整个递归结束时,maxDepth(root)返回root的深度。