Sword Finger Offer Interview Question 55-2: Balanced Binary Tree

My initial thought on this question was to traverse the left and right subtrees for each node, but such a method has a time complexity of n^2. I didn't think of a better method, so I just looked at the answer.

 

 

Answer method: ( https://leetcode-cn.com/problems/ping-heng-er-cha-shu-lcof/solution/mian-shi-ti-55-ii-ping-heng-er-cha-shu- cong-di-zhi/ )

Post-order traversal, pruning

When the difference between the left and right subtrees is greater than 2, return -1. This -1 is used for pruning and directly ends all recursion. In this way, the judgment of true and false becomes a judgment of whether it is -1.

If root is null, then directly return 0, which means that the depth provided by the location is 0.

However, in this calculation method, each node gets the depth from the bottom up, not from the top down, but it does not affect the problem-solving.

 

    public boolean isBalanced(TreeNode root) {
        return  recur(root)!=-1;
    }
    public int recur(TreeNode root){
        if(root == null){
            return 0;
        }
        int left = recur(root.left);
        if(left == -1) return -1;
        int right = recur(root.right);
        if(right == -1) return -1;

        return Math.abs(left-right)<2?Math.max(left,right)+1:-1;
        
    }

 

 

 

 

 

 

 

 

Guess you like

Origin blog.csdn.net/qq_40473204/article/details/115006970