簡體   English   中英

在二叉樹中查找最大高度/深度

[英]Finding max height/depth in Binary Tree

在了解了二叉樹的基礎知識后,我在 C++ 中定義如下:

struct Node
{
    int key;
    Node *left;
    Node *right;
}*left=NULL,*right=NULL;

int getDepth(Node* t)
{
  if (t == NULL)
    return 0;
  else
    {
      int lDepth = getDepth(t->left);
      int rDepth = getDepth(t->right);

      if (lDepth > rDepth)
        return(lDepth + 1);
      else 
        return(rDepth + 1);
    }
}
int main()
{
    // root
    Node* root = new Node();
    root->key = 1;
    
    // left subtree
    root->left = new Node();
    root->left->key = 2;
    root->left->left = new Node();
    root->left->left->key = 4;
    root->left->right = new Node();
    root->left->right->key = 5;
    
    // right subtree
    root->right = new Node();
    root->right->key = 3;
}

現在,如果我嘗試使用此代碼找到最大高度/深度,它會返回 3 而不是 2。可能是什么原因? 另外,為什么我沒有找到這種為任何地方的節點分配價值的方式?

編輯:添加請求的代碼

兩個問題:

1.您錯誤地設置了 struct Node

要定義成員具有初始值的類型Node ,您的語法略有錯誤。 相反,請執行以下操作:

struct Node {
    int key = 0;
    Node *left = nullptr;
    Node *right = nullptr;
};

2. 樹的高度是 3。

這是您創建的樹的可視化表示。 它有3個級別。

         1
        / \
       2   3
      / \
     4   5

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM