public class Solution {
public boolean isBalanced(TreeNode root) {
if (root == null) return true;
if(Math.abs(depth(root.left)  depth(root.right)) > 1) return false;
return isBalanced(root.left) && isBalanced(root.right);
}
private int depth(TreeNode node){
return node==null?0:1+Math.max(depth(node.left), depth(node.right));
}
}
Java 2ms solution (recursion)


I submitted something similar and it's accepted.
It still have something to optimize but I haven't figured it out yet :
let's take "root" as parameter (has both left & right child), the depth of root.left & root.right are figured out at first, and then it will get the depth of children of root.left and root.right separately again. The depth of those nodes are calculated several times (== the level in the tree, root at level 0). Do you have a better way? thanks

@qiuping345 Honestly I haven't looked too much into optimizing solutions yet. Still working on my first time through the questions here. I'll revisit my old solutions and see if I can improve upon them after I finish solving all of the current questions!