二叉搜索树的深度

depth of a binary search tree

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

所以我需要用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;
};