平衡二叉樹

題目描述

輸入一棵二叉樹,判斷該二叉樹是不是平衡二叉樹。java

思路

深度搜索,剪枝。
時間複雜度O(lgn),空間複雜度O(lgn)。code

未剪枝代碼

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

剪枝代碼

public class Solution {
    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;
        }
        return Math.abs(left-right) < 2 ? 1 + Math.max(left, right) : -1;
    }
    
    public boolean IsBalanced_Solution(TreeNode root) {
        return depth(root) != -1;
    }
}
相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息