Java solution 2ms recursion, easy to understand..


  • 3
    public class Solution {
    public boolean isBalanced(TreeNode root) {
        if(root==null) return true;
        int height=depth(root.left)-depth(root.right);
        if(height>1||height<-1) return false;
        else return isBalanced(root.left)&&isBalanced(root.right);
    }
    private int depth(TreeNode root){
        if(root==null) return 0;
        int l=depth(root.left);
        int h=depth(root.right);
        return (l>h?l:h)+1;
    }
    

    }


Log in to reply
 

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