二叉搜索树的深度 >我需要在C++中写一个函数,返回树的深度。我有点不明白这意味着什么。它是每个单独节点的深度,或者是整个树的深度。例如,树有4个级别。任何帮助都将不胜感激

二叉搜索树的深度 >我需要在C++中写一个函数,返回树的深度。我有点不明白这意味着什么。它是每个单独节点的深度,或者是整个树的深度。例如,树有4个级别。任何帮助都将不胜感激,c++,binary-search-tree,treenode,C++,Binary Search Tree,Treenode,树的深度是最深节点的级别。这看起来是个很好的定义。话虽如此,这里是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 = height

树的深度是最深节点的级别。这看起来是个很好的定义。话虽如此,这里是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);
};

这通常指的是整棵树的深度。但请注意,树的深度可能不一致,即树的某些叶子位于深度3,而某些叶子位于深度4,在这种情况下,树的深度将为4。您可能需要查看“树的深度”的定义?一个好主意是在添加或移动新节点时更新深度和节点计数。对此,抱歉?我不知道除此之外,在这里使用宏会大大降低代码效率。正如Valeri所说,最好将深度返回存储在变量中,然后在变量上运行宏。每个节点都要计算两次深度。请不要在方法名(或变量名)的开头加下划线。这样的名字是保留的。
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;
};