gpt4 book ai didi

c++ - 我正在尝试使用此代码查找二叉树的高度,但它始终返回0,有人可以告诉我为什么吗?

转载 作者:行者123 更新时间:2023-12-02 10:36:47 25 4
gpt4 key购买 nike

我正在尝试使用此代码查找二叉树的高度,但它始终返回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)传递结果参数。在这种情况下,没有返回值。但是,这是一种编码风格,我主要只在硬件编程中才能看到。

否则,您可以返回结果。您已经有一个返回参数,只需修正该值的实际用法即可,因为您的代码将忽略它。

这是两种方法:

使用返回参数:

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

关于c++ - 我正在尝试使用此代码查找二叉树的高度,但它始终返回0,有人可以告诉我为什么吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59924994/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com