My 10-line recursion solution


  • 4
    H
    public class Solution {
        public boolean isBalanced(TreeNode root) {
            if(root == null) return true;
            if(Math.abs(height(root.left) - height(root.right)) > 1) return false;
            return isBalanced(root.left) && isBalanced(root.right);
        }
        public int height(TreeNode node){
            if(node == null) return 0;
            return Math.max(height(node.left), height(node.right)) + 1;
        }
    }

  • 2
    A

    Maybe to store the TreeNode's height into a HashMap is a better idea. That avoids calculating height of child nodes time and time again.


Log in to reply
 

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