我试图用这段代码找到二叉树的高度,但它一直返回 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?

本文关键字:返回 一直 为什么 告诉我 高度 段代码 代码 二叉树      更新时间:2023-10-16

我试图用这段代码找到二叉树的高度,但它一直返回 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;
}