[英]Finding max height/depth in Binary Tree
After going through the basics of Binary Tree, I define it in C++ as below:在了解了二叉树的基础知识后,我在 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;
}
Now If I try to find maximum height/depth using this code, it returns 3 instead of 2. What may be the reason?现在,如果我尝试使用此代码找到最大高度/深度,它会返回 3 而不是 2。可能是什么原因? Also, Why I didn't find this way of assigning value to nodes anywhere?
另外,为什么我没有找到这种为任何地方的节点分配价值的方式?
Edit: Adding requested code编辑:添加请求的代码
Two issues:两个问题:
Node
. Node
。 To define a type Node
where the members have initial values, your syntax is slightly wrong.要定义成员具有初始值的类型
Node
,您的语法略有错误。 Instead, do:相反,请执行以下操作:
struct Node {
int key = 0;
Node *left = nullptr;
Node *right = nullptr;
};
Here's a visual representation of the tree you've created.这是您创建的树的可视化表示。 It has 3 levels.
它有3个级别。
1
/ \
2 3
/ \
4 5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.