Java Recursive Solution with comments

  • 1
    public class Solution {
        //helper function to find the depth of a tree from a given node 
        public Integer depthOfTree(TreeNode root){
            if(root == null)
                return 0;
            return 1 + Math.max(depthOfTree(root.left), depthOfTree(root.right));
        public boolean isBalanced(TreeNode root) {
            if(root == null)
                return true;
            //find the depth on the left and right sub trees 
            int lDepth = depthOfTree(root.left);
            int rDepth = depthOfTree(root.right);
            //if the difference is greater than 1 return false
            if(Math.abs(lDepth-rDepth) > 1){
                return false;
            //recur on every node of the tree 
            return isBalanced(root.left) && isBalanced(root.right);

Log in to reply

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