How to determine if binary tree is balanced?

前端 未结 27 1478
萌比男神i
萌比男神i 2020-11-30 16:11

It\'s been a while from those school years. Got a job as IT specialist at a hospital. Trying to move to do some actual programming now. I\'m working on binary trees now, a

27条回答
  •  自闭症患者
    2020-11-30 17:01

    Note 1: The height of any sub-tree is computed only once.

    Note 2: If the left sub-tree is unbalanced then the computation of the right sub-tree, potentially containing million elements, is skipped.

    // return height of tree rooted at "tn" if, and only if, it is a balanced subtree
    // else return -1
    int maxHeight( TreeNode const * tn ) {
        if( tn ) {
            int const lh = maxHeight( tn->left );
            if( lh == -1 ) return -1;
            int const rh = maxHeight( tn->right );
            if( rh == -1 ) return -1;
            if( abs( lh - rh ) > 1 ) return -1;
            return 1 + max( lh, rh );
        }
        return 0;
    }
    
    bool isBalanced( TreeNode const * root ) {
        // Unless the maxHeight is -1, the subtree under "root" is balanced
        return maxHeight( root ) != -1;
    }
    

提交回复
热议问题