I am trying to find the height of a Binary tree with this code, but it keeps returning 0, can someone please tell me why?
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
}
You're mixing up two ways of doing things. Either pass the result parameter, using a pointer or an address (int*
and &maxheight
). In this case there is no return value. But tbh, this is a coding style I've mainly only seen in hardware programming.
Otherwise you can return a result. You already have a return parameter in place, just fix the actual usage of the value because your code ignores it.
Here's the two ways to do it:
Using return parameter:
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
}
Using pointer parameters. Note that rootheight is local to each branch so don't pass it as a pointer.
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;
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments