剑指offer 55_平衡二叉树(java)

平衡二叉树-II

输入一棵二叉树,判断该二叉树是否是平衡二叉树(它是一 棵空树或它的左右两个子树的高度差的绝对值不超过1)。

在这里,我们只需要考虑其平衡性,不需要考虑其是不是排序二叉树

方法1:自顶向下

思路分析:

从根节点出发开始递归,依次判断左右子树的深度差是否<1,同时还要判断当前的左右子树是否平衡;
递归条件:左右子树深度差<1且左右子树均为平衡树;
终止条件:上述的非命题

复杂度

时间复杂度:O(NlogN) 每层节点的求深度操作O(N)*树的深度遍历O(logN)
空间复杂度:O(N)

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

方法2: 自底向上

对二叉树做后序遍历,从底至顶返回子树深度,若判定某子树不是平衡树则 “剪枝” ,直接向上返回。

public class Solution {
    public boolean IsBalanced_Solution(TreeNode root) {
        if(root == null) return true;
        if(depth(root) == -1) return false;
        else return true;
        
    }
    
    private int depth(TreeNode root){
        if(root == null) return 0;
        int left = depth(root.left);
        if(left == -1) return -1;
        int right = depth(root.right);
        if(right == -1) return -1;
        if(Math.abs(left - right) <= 1){
            return Math.max(left, right) + 1;
        }else{
            return -1;
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章