Easy to understand O(n) JAVA solution


  • 0
    J
    public class Solution {
        public boolean isBalanced(TreeNode root) {
            return depth(root)!=-1;
        }
        private int depth(TreeNode root){
            if(root==null){
                return 0;
            }
            int left = depth(root.left);
            int right = depth(root.right);
            if(left==-1||right==-1||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.