Share my Java solution,1ms

  • 1
        //方法一 2ms
    	public boolean isBalanced(TreeNode root){
    		if(root==null) return true;
    		int leftdep = helper(root.left,0);
    		int rightdep = helper(root.right,0);
    		if(Math.abs(leftdep-rightdep)>1) return false;
    		return isBalanced(root.left)&&isBalanced(root.right);
    	private int helper(TreeNode node,int depth){
    		if(node==null) return depth;
    		int leftdep = helper(node.left,depth+1);
    		int rightdep = helper(node.right,depth+1);
    		return leftdep>rightdep?leftdep:rightdep;
    	//方法二 1ms
    	public boolean isBalanced(TreeNode root){
    		return helper(root)<0?false:true;
    	private int helper(TreeNode root){
    		if(root==null) return 0;
    		int left = helper(root.left);
    		if(left<0) return -1;
    		int right = helper(root.right);
    		if(right<0) return -1;
    		if(Math.abs(left-right)>1) return -1;
    		return Math.max(left, right)+1;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.