【发布时间】:2021-05-20 14:17:59
【问题描述】:
在了解了二叉树的基础知识后,我在 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.您错过了添加计算深度的代码。 2.您错过了初始化子节点指针。
struct Node { /*... */ } *left = NULL, *right = NULL;创建两个Node*类型的全局变量。如果您想提供默认值,则必须如下所示:struct Node { Node* left = nullptr; Node* right = nullptr; };(旁注:nullptr是 C++ keyword 您应该更喜欢旧/过时的 C macros(NULL). -
添加完整代码
标签: c++ c++11 data-structures