Hello guys, I'm trying to understand how I can see if a binary tree is balanced or not. I tried to print out cout statements in order to try understand it further, but without luck.
The algorithm idea is that it isn't balanced if it returns -1, and is balanced if it returns anything else.
However I don't really grasp how exactly this algorithm is working. But a few things I wonder are;
int checkBalance(node *root)
{
if (root == NULL) return 0;
int left = checkBalance(root->left);
int right = checkBalance(root->right);
//cout << "Root: " << root->key << " Left: " << left << ", Right: " << right << endl;
if (left == -1 || right == -1) return -1;
if (abs(left-right) > 1) return -1;
if (left > right) return left+1;
return right+1;
}
My points of confusion are with the following lines of code:
- if (root == NULL) return 0;
- What happens when it returns 0, and when does it hit 0? Is it just to prevent the recursion to keep going to unknown memory adresses, or does the return number 0 has any significance?
if (left > right) return left+1;
- How is left ever bigger than right? As I'm viewing it, it always returns right+1, cause nothing increments 'left' since the condition never is true?
int left = checkBalance(root->left);
- What does it mean, when you declare an int in this way? Is this the thing which makes left > right?
Thanks for taking your time to read, I have tried to research the problem myself, but I have a hard time understanding how this piece of code works.
Full Code: http://pastebin.com/raw/VaiUNVdJ (case 6 to check, case 1 to add nodes)