Java recursive O(N) solution


  • 0
    Z
    public class Solution {
        public boolean isBalanced(TreeNode root) {
            if(root==null) return true;
            
            int len = getHeight(root);
            
            return len<0? false: true;
        }
        
        int getHeight(TreeNode root){
            if(root==null) return 0;
            int left = getHeight(root.left);
            int right = getHeight(root.right);
            int len = -1;
            if(left >=0 && right >=0){
                if(Math.abs(left - right) <= 1){
                    len =  Math.max(left, right)+1;
                }
            }
            return len;
        }
    }
    

Log in to reply
 

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