Java 2ms solution (recursion)


  • 0
    I
    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));
        }
    }
    

  • 0

    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


  • 0
    I

    @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!


Log in to reply
 

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