jeudi 20 mai 2021

Finding max height/depth in Binary Tree

After going through the basics of Binary Tree, I define it in C++ as below :

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

Now If I try to find maximum height/depth using this code, it returns 3 instead of 2. What may be the reason? Also, Why I didn't find this way of assigning value to nodes anywhere?

Edit: Adding requested code

Aucun commentaire:

Enregistrer un commentaire