Easy Java solution - 3ms


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

Log in to reply
 

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