我试图用这段代码找到二叉树的高度,但它一直返回 0,有人可以告诉我为什么吗?
I am trying to find the height of a Binary tree with this code, but it keeps returning 0, can someone tell me why?
我试图用这段代码找到二叉树的高度,但它一直返回 0,有人可以告诉我为什么吗?
int heightHelper(Node* root, int maxheight, int rootheight)
{
if (root->right == nullptr && root->left == nullptr) { //checks if the node has a child
if (maxheight < rootheight) {
maxheight = rootheight;
}
}
else { //if it has then increase height by 1
rootheight += 1;
if (root->left != nullptr) {
heightHelper(root->left, maxheight, rootheight);
}
if (root->right != nullptr) {
heightHelper(root->right, maxheight, rootheight);
}
}
return maxheight; //return height
}
int height(Node* root)
{
// Write your code here.
return heightHelper(root, 0, 0); //root node base case
}
你混淆了两种做事方式。使用指针或地址传递结果参数(int*
和&maxheight
(。在这种情况下,没有返回值。但是tbh,这是一种编码风格,我主要只在硬件编程中看到。
否则,您可以返回结果。您已经有一个返回参数,只需修复该值的实际用法,因为您的代码会忽略它。
以下是两种方法:
使用返回参数:
int heightHelper(Node* root, int height)
{
if (root->right == nullptr && root->left == nullptr) { //checks if the node has a child
return height;
}
else { //if it has then increase height by 1
height += 1;
int maxheight1;
int maxheight2;
if (root->left != nullptr) {
maxheight1 = heightHelper(root->left, height);
}
if (root->right != nullptr) {
maxheight2 = heightHelper(root->right, height);
}
// return maximum of the two
if (maxheight1 > maxheight2) return maxheight1;
else return maxheight2;
}
}
int height(Node* root)
{
// Write your code here.
return heightHelper(root, height); //root node base case
}
使用指针参数。请注意,rootheight 是每个分支的本地部分,因此不要将其作为指针传递。
void heightHelper(Node* root, int* maxheight_ptr, int rootheight)
{
if (root->right == nullptr && root->left == nullptr) { //checks if the node has a child
if (*maxheight < rootheight) {
*maxheight = rootheight;
}
}
else { //if it has then increase height by 1
rootheight += 1;
if (root->left != nullptr) {
heightHelper(root->left, maxheight_ptr, rootheight);
}
if (root->right != nullptr) {
heightHelper(root->right, maxheight_ptr, rootheight);
}
}
}
int height(Node* root)
{
// Write your code here.
int maxheight = 0;
heightHelper(root, &maxheight, 0); //pass the addresses of variables
return maxheight;
}
相关文章:
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- 什么时候在C++中返回常量引用是个好主意
- 你能重载对象变量名本身返回的内容吗
- 为什么 Serial.println(<char[]>);返回随机字符?
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 如何获取std::result_of函数的返回类型
- 我试图用这段代码找到二叉树的高度,但它一直返回 0,有人可以告诉我为什么吗?
- C++ libssh - ssh_channel_read() 一直返回 0,ssh_channel_is_open()
- 我的代码一直返回0作为文本文件中的小数数
- 我的bool函数一直返回true,我不知道为什么
- 我正在尝试编写一个简单的计算程序,但答案一直返回为 0
- 我一直为变量howMany返回相同的值
- 为什么我的代码在完成之前一直返回
- 尝试返回 area 的对象成员,但一直得到 0
- Atoi()一直返回0
- 选择函数一直返回-1
- 函数一直返回NaN
- c++ rand()一直返回相同的数字
- 不知道为什么我的函数一直返回相同的值
- is_member_function_pointer一直返回true