Sword Finger offer-Balanced Binary Tree

Posted by www.WeAnswer.IT on Mon, 07 Oct 2019 00:06:39 +0200

Title Description

Input a binary tree to determine whether the binary tree is a balanced binary tree.

way1

Thought (offer)

The depth difference between the left and right subtrees of the balanced binary tree is not more than 1. https://blog.csdn.net/weixin_44135282/article/details/100579216
Find the depth of left and right subtrees and judge the difference. If the difference does not exceed 1, it is a balanced binary tree.

java implementation

public class Solution {
    public boolean IsBalanced_Solution(TreeNode root) {
        if(root==null)
            return true;
        int left=TreeDepth(root.left);
        int right=TreeDepth(root.right);
        int minusabs=Math.abs(left-right);
        boolean result=false;
        if(minusabs<=1)
            result=true;
        return result;
    }

    public int TreeDepth(TreeNode root) {
        if(root==null)
            return 0;
        int left=TreeDepth(root.left);
        int right=TreeDepth(root.right);
        return left>right? left+1:right+1;
    }
}

Way2

thinking

Method 1 repeats the traversal of nodes, which has poor performance.
Improvement: After traversing the whole binary tree, traversing to the left and right sub-nodes of a node, judging whether the balance is based on the depth of the left and right nodes, and getting the depth of the current node. When traversing to the root node, it is judged whether the whole binary tree is a balanced binary tree.

Realization

public class Solution {
    private boolean isBalanced = false;//Final Return Value
    public boolean IsBalanced_Solution(TreeNode root) {
        if(root == null) 
            return true;
        getDepth(root);
        return isBalanced;
    }
    public int getDepth(TreeNode root) {
        if(root == null) 
            return 0;
        int left = getDepth(root.left);//Left tree
        int right = getDepth(root.right);//Right subtree
        int depth = (left > right ? left : right) + 1;
        if(Math.abs(left - right) <= 1) {
            isBalanced = true;
        } else {
            isBalanced = false;
        }
        return depth;//The depth of the lower layer, the upper layer can be used to avoid traversing again
    }
}

Topics: Java