How to add a node that will always stay defined?

closed account (18hRX9L8)
Hello,

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).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <cstdlib>
#include <cstdio>
#include <cmath>

typedef struct Node *Tree;
typedef struct Node {
	int value;
	Tree left, right;
} *Tree;

int treeHeight(Tree tree) { // Always gives me 0.
	if(tree == NULL) {
		return 0;
	}
	
	const int left = treeHeight(tree->left);
	const int right = treeHeight(tree->right);
	
	return 1 + (left > right) ? left : right;
}

bool isBalanced(Tree tree) { // Always gives me 'true';
	if(tree == NULL) {
		return true;
	}
	
	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?

Thank you,
Usandfriends
Last edited on
Topic archived. No new replies allowed.