"Sword Finger Offer"-39. Balanced Binary Tree

1. Knowledge points of this question

tree

2. Title description

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

Here, we only need to consider its balance, not whether it is a sorted binary tree.

The Balanced Binary Tree has the following properties: it is an empty tree or the absolute value of the height difference between its left and right subtrees does not exceed 1, and the left and right subtrees are both a balanced binary tree.

E.g:

输入:
{1,2,3,4,5,6,7}

返回值:
true

3. Problem solving ideas

Use post-order traversal: left subtree, right subtree, root node, you can first recursive to the leaf node, and then in the process of backtracking to determine whether the conditions are met.

4. Code

public class TreeNode {
    
    
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
    
    
        this.val = val;
    }
}
public class Solution {
    
    
    public boolean isBalanced_Solution(TreeNode root) {
    
    
        // 它是一棵空树,则是平衡的
        if (root == null) {
    
    
            return true;
        }
        int depth = getDepth(root);
        if (depth == -1) {
    
    
            return false;
        }
        return true;
    }

    /**
     * 返回当前节点的深度
     * @param root
     * @return
     */
    public int getDepth(TreeNode root) {
    
    
        // 叶节点深度为 0
        if (root == null) {
    
    
            return 0;
        }
        int left = getDepth(root.left);
        // 遍历过程中发现子树不平衡
        if (left == -1) {
    
    
            return -1;
        }
        int right = getDepth(root.right);
        // 遍历过程中发现子树不平衡
        if (right == -1) {
    
    
            return -1;
        }
        // 左右两个子树的高度差的绝对值超过 1,则不平衡
        if (Math.abs(left - right) > 1) {
    
    
            return -1;
        }
        // 返回当前节点的深度
        return left > right ? left + 1 : right + 1;
    }
}

Guess you like

Origin blog.csdn.net/bm1998/article/details/112797034