I am having a problem with inputting a variable type Tree as a function parameter. When I call these functions on the variable, it gives me 0 or true (meaning the variable is NULL).
#include <cstdlib>
#include <cstdio>
#include <cmath>
typedefstruct Node *Tree;
typedefstruct Node {
int value;
Tree left, right;
} *Tree;
int treeHeight(Tree tree) { // Always gives me 0.
if(tree == NULL) {
return 0;
}
constint left = treeHeight(tree->left);
constint right = treeHeight(tree->right);
return 1 + (left > right) ? left : right;
}
bool isBalanced(Tree tree) { // Always gives me 'true';
if(tree == NULL) {
returntrue;
}
return isBalanced(tree->left) && isBalanced(tree->right) && (std::abs(treeHeight(tree->left) - treeHeight(tree->right)) <= 1);
}
Tree newNode(int value) {
Tree tree = Tree(malloc(1 * sizeof(Node)));
tree->value = value;
tree->left = NULL;
tree->right = NULL;
return tree;
}
int main(void) {
Tree tree = newNode(100);
tree->left = newNode(10);
tree->right = newNode(40);
tree->left->left = newNode(20);
tree->left->left->left = newNode(15);
printf("%d , %s, %d", treeHeight(tree), isBalanced(tree) ? "TRUE" : "FALSE", tree->left->left->left->value); // This prints out fine, meaning the variable is not NULL in this scope....
getchar();
free(tree);
return 0;
}
The variable is fine in the main function scope but is NULL in the other functions' scopes. How do I create a new node and preserve it for the rest of the program?