「ソードフィンガーオファー」-39。バランス二分木

1.この質問の知識ポイント

2.タイトルの説明

二分木を入力して、二分木が平衡二分木であるかどうかを判別します。

ここでは、それがソートされた二分木であるかどうかではなく、そのバランスを考慮する必要があるだけです。

平衡二分木には次の特性があります。空の木であるか、左右のサブツリー間の高さの差の絶対値が1を超えず、左右のサブツリーは両方とも平衡二分木です。

例えば:

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

返回值:
true

3.問題解決のアイデア

ポストオーダートラバーサルを使用します:左サブツリー、右サブツリー、ルートノード、最初にリーフノードに再帰し、次にバックトラックのプロセスで条件が満たされているかどうかを判断できます。

4.コード

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;
    }
}

おすすめ

転載: blog.csdn.net/bm1998/article/details/112797034