AVL-tree calculate height difference

I looking for method which can give me the height difference of an AVL_tree.

The method i come up with up now is this.

1
2
3
4
5
6
7
8
9
10
11
int avl_tree::balance(node* pointer)
{
    
    while (pointer->left != NULL) {
        int left = balance(pointer ->left);
    }
    while (pointer->right != NULL) {
       int right = balance(pointer->right);
    }
    return  left - right;
}


Which recursively calls itself, but the problem is that i get stuck on the first line..

Anyone with an better idea?
Last edited on
Anyone with an better idea?

Don't loop on a value that cannot change? If pointer->left is not NULL, it will always be not NULL.
I don't see how else you would do it without looping towards the root?
Recursion is a form of iteration.
Take a look at the way I did it here:
http://www.cplusplus.com/forum/beginner/108093/#msg588108

Note that balancing avl tree is not something you do AFTER you have inserted elements into the tree. There is a reason why avl trees are very tightly balanced and it is because of the rigorous work that goes into keeping them balanced. As you will see from the code I have, the tree is balanced pretty much after every other insertion (difference between height of left and right has to be 1 or less)

Updated version: https://drive.google.com/file/d/0B3YhWUWL5lcga1VJOFJud1gyMms/view
Last edited on
Topic archived. No new replies allowed.