开发者

Doubt Regarding Function to check whether a tree is balanced or not?

开发者 https://www.devze.com 2023-03-25 07:33 出处:网络
I read in a book named \"Coding Interview Cracked\", that to check whether a BST is balanced or not, just find out the difference betw开发者_开发知识库een the maximum and minimum height but I not sure

I read in a book named "Coding Interview Cracked", that to check whether a BST is balanced or not, just find out the difference betw开发者_开发知识库een 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


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消