Share my easiest understand and 2ms Solution , O(N)


  • 1
    C
    public boolean isBalanced(TreeNode root) {
        int res = heightOfTree(root);
        return res != -1;
    }
    
    // if the tree is balanced , return the height of the tree
    // if the tree is unbalanced,  return -1 to denote it isn't balanced
    public int heightOfTree(TreeNode root) {
        if (root == null) { 
            return 0;
        }
        if (root.left == null && root.right == null) {
            return 1;
        }
        int left = heightOfTree(root.left);
        int right = heightOfTree(root.right);
        if (left == -1 || right == -1 || Math.abs(left - right) > 1) {
            return -1;
        }
        return 1 + Math.max(left, right);
    }

  • 0
    A

    not good because you should return when you find the result contains -1.


  • 0
    C

    you have to do this because you don't know whether the tree is balance or not


  • 0
    A

    your method is dull. Please consider, when left value is -1, shall we still need to compute the right value ?


  • 0
    C

    I see , THANKS A LOT


Log in to reply
 

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