繁体   English   中英

二叉搜索树的深度

[英]depth of a binary search tree

所以我需要用c ++编写一个返回树的深度的函数。 我对此有点困惑。 它是每个单个节点的深度,还是整个树的深度,例如,树具有4个级别。 任何帮助,将不胜感激

树的深度是最深节点的级别。 看起来不错。 话虽如此,这是C ++中一个类的实现,其中root是该类的属性。 基本上,您将获得左侧子树的深度和右侧子树的深度,并选择两者中最大的一个。

#define max(a,b)  ((a)>=(b) ? (a) : (b))



int height2(Node *t) {
  if(!t) 
    return 0;
  int height_left  = height2(t->L);
  int height_right = height2(t->R);
  return 1 + max(height_left,height_right);
};


int height() {
  return height2(root);
};
class Node {
public:
    //...
    unsigned int depth() {
        return 1 + max(depth(left),
                       depth(right));
    }
private:
    unsigned int depth(Node* node) {
        return node ? node->depth() : 0;
    }
    Node* left;
    Node* right;
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM