How to determine if binary tree is balanced?

前端 未结 27 1532
萌比男神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 16:44

    Here is a version based on a generic depth-first traversal. Should be faster than the other correct answer and handle all the mentioned "challenges." Apologies for the style, I don't really know Java.

    You can still make it much faster by returning early if max and min are both set and have a difference >1.

    public boolean isBalanced( Node root ) {
        int curDepth = 0, maxLeaf = 0, minLeaf = INT_MAX;
        if ( root == null ) return true;
        while ( root != null ) {
            if ( root.left == null || root.right == null ) {
                maxLeaf = max( maxLeaf, curDepth );
                minLeaf = min( minLeaf, curDepth );
            }
            if ( root.left != null ) {
                curDepth += 1;
                root = root.left;
            } else {
                Node last = root;
                while ( root != null
                 && ( root.right == null || root.right == last ) ) {
                    curDepth -= 1;
                    last = root;
                    root = root.parent;
                }
                if ( root != null ) {
                    curDepth += 1;
                    root = root.right;
                }
            }
        }
        return ( maxLeaf - minLeaf <= 1 );
    }
    

提交回复
热议问题