1

I read in a book named "Coding Interview Cracked", that to check whether a BST is balanced or not, just find out the difference between the maximum and minimum height but I not sure whether it is 100% correct. Though I am unable to find a counter test case.

Can anyone confirm whether this approach is correct or not.

For checking whether a tree is balanced or not.

|MaxHieght(root) - MinHieght(root)| <=1
   return true
else return false
ua741
  • 1,446
  • 15
  • 28

2 Answers2

3

Given the definition of balanced (from the Wiki of Pedias)

The balance factor of a node is the height of its left subtree minus the height of its right subtree (sometimes opposite) and a node with balance factor 1, 0, or −1 is considered balanced. A node with any other balance factor is considered unbalanced and requires rebalancing the tree. The balance factor is either stored directly at each node or computed from the heights of the subtrees.

This seems correct. Since the minHeight and maxHeight are going to be equal to the height of either side, looks like the definition holds

dfb
  • 13,133
  • 2
  • 31
  • 52
0

You can try this way also, if you feel like.

bool isBalanced(node curPtr)
{
        static int heightLeft,heightRight; //Need to save previous return value

        if ( !curPtr )
        {
                return 0;
        }

        heightLeft  = isBalanced(curPtr->lChild);
        heightRight = isBalanced(curPtr->rChild);

        ++heightLeft;   // Height of the Tree should be atleast 1 ( ideally )
        ++heightRight;


        return ( ( ( heightLeft - heightRight ) == 0 ) || (( heightRight - heightLeft ) == 0 ) );
}

HTH

Kelly
  • 213
  • 1
  • 6
  • 21