I have the following function to computer height of a node in a binary tree (and its descendants):
void computeHeight(Node *n) {
// Implement computeHeight() here.
if (n->left) {
computeHeight(n->left);
int leftHeight = n->left->height;
} else {
int leftHeight = -1;
}
if (n->right) {
computeHeight(n->right);
int rightHeight = n->right->height;
} else {
int rightHeight = -1;
}
n->height = std::max(leftHeight, rightHeight) 1;
}
When I run the code I have error: ‘leftHeight’ was not declared in this scope
, it happens at line n->height = std::max(leftHeight, rightHeight) 1;
. The error happens during compilation.
I don't understand why it happens because I defined leftHeight
above.
Other code:
In main.cpp
:
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <string>
#include <queue>
#include "main.h"
void computeHeight(Node *n) {}
int main() {
Node *n = new Node();
n->left = new Node();
n->right = new Node();
n->right->left = new Node();
n->right->right = new Node();
n->right->right->right = new Node();
computeHeight(n);
std::cout << std::endl << std::endl;
delete n;
n = nullptr;
return 0;
}
In main.h
:
class Node {
public:
int height; // to be set by computeHeight()
Node *left, *right;
Node() { height = -1; left = right = nullptr; }
~Node() {
delete left;
left = nullptr;
delete right;
right = nullptr;
}
};
CodePudding user response:
Comments and Anoop answer your question. You need to read more about scopes in programming. Functions, loops, conditional statements create their own scopes. Variables created inside those scopes are local to those scopes.
In C you can create your own scope by just putting braces:
int main () {
int y = 1;
{
int x = 2;
y = x; // no error
}
x = y; // error
}
A cleaner working version of your code is the following:
void computeHeight(Node *n) {
int leftHeight = -1;
int rightHeight = -1;
// Implement computeHeight() here.
if (n->left) {
computeHeight(n->left);
leftHeight = n->left->height;
}
if (n->right) {
computeHeight(n->right);
rightHeight = n->right->height;
}
n->height = std::max(leftHeight, rightHeight) 1;
}
CodePudding user response:
The problem is that you have defined leftHeight
inside if
else
block and therefore they are not visible outside of those blocks. Similarly the variable rightHeight
is also visible only inside the blocks in which it was defined.
To solve this just define leftHeight
outside(of those blocks) once and then just assign value to them inside if
and else
blocks which would look like:
void computeHeight(Node *n) {
int leftHeight = -1;//define and initialize leftHeight
int rightHeight = -1;//define and initialize rightHeight
// Implement computeHeight() here.
if (n->left) {
computeHeight(n->left);
leftHeight = n->left->height;//note this is assignment
}
if (n->right) {
computeHeight(n->right);
rightHeight = n->right->height;//note this is assignment
}
n->height = std::max(leftHeight, rightHeight) 1;//this works now
}