41.平衡二分木

件名の説明:

  二分木のルートノードを入力し、ツリーはないバランスの取れた二分木と判定され

アイデアの分析:

  溶液1:左と右の部分木の高さの差が1以上、その左側のサブツリーを決定するために、継続しない場合は、左と右のサブツリーが平衡二分木である場合にサブツリーのルートの周囲に決定高さは、平衡二分木ではなく、そして、最終的にツリーは平衡二分木です。

  解決策2:単純に明確な思考で解決策1が、横断ノードが複数回繰り返され、このアイデアの時間効率は高くありません。私たちは、私たちが左右することができ、私たちはその左と右のサブツリーを横断しなければならなかったの前に、各ノードのその横断中に限り、レコードの深さなど、ノードへのトラバース、バイナリツリーの各ノードを通過する、道を後順ムラを横断しながら、各ノードを分析します。

コード:

public class Solution {
    public boolean IsBalanced_Solution(TreeNode root) {
        if(root==null)
            return true;
        int left=depth(root.left);
        int right=depth(root.right);
        if(Math.abs(left-right)>1)
            return false;
        return IsBalanced_Solution(root.left)&&IsBalanced_Solution(root.right);
    }
    public int depth(TreeNode root){
        if(root==null)
            return 0;
        int left=depth(root.left);
        int right=depth(root.right);
        return Math.max(left,right)+1;
    }
}
public class Solution {
    boolean res=true;
    public boolean IsBalanced_Solution(TreeNode root) {
        if(root==null)
            return res;
        depth(root);
        return res;
    }
    public int depth(TreeNode root){
        if(root==null)
            return 0;
        int left=depth(root.left);
        int right=depth(root.right);
        if(Math.abs(left-right)>1)
            res=false;
        return Math.max(left,right)+1;
    }
}

おすすめ

転載: www.cnblogs.com/yjxyy/p/10932559.html