4.1 isBalanced tree

来源:互联网 发布:动漫手机壳淘宝哪家店 编辑:程序博客网 时间:2024/06/16 16:07

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.



O(N2)soln



public class Solution {

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

}

0(N) time and 0(H) space,soln

    public boolean isBalanced(TreeNode root) {
        if (root==null) return true;
        if(checkDept(root)<0)return false;
        return true;
    }
    private int checkDept(TreeNode node){
        if(node==null) return 0;
        if (node.left==null&& node.right==null) return 1;
        if(checkDept(node.left)<0||checkDept(node.right)<0) return -1;
        if (Math.abs(checkDept(node.left)-checkDept(node.right))>1) return -1;
        return 1+Math.max(checkDept(node.left),checkDept(node.right));
    }
    
}



0 0
原创粉丝点击