问题描述
在了解二叉树的基础知识后,我在 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.您错误地设置了结构 Node
。
要定义成员具有初始值的类型 Node
,您的语法略有错误。相反,请执行以下操作:
struct Node {
int key = 0;
Node *left = nullptr;
Node *right = nullptr;
};
2.树的高度为 3。
这是您创建的树的可视化表示。它有 3 个级别。
1
/ \
2 3
/ \
4 5