Javascript recursive solution

  • 0
    var isBalanced = function(root) {
        if(!root) return true;
        getHeight(root);//get all height of node and stored in the node itself
        var leftHeight = root.left?root.left.height:0;//if left child is null, set its height as 0
        var rightHeight = root.right?root.right.height:0;//if right child is null, set its height as 0
        if(Math.abs(leftHeight - rightHeight) > 1) return false;//if the root is not a balanced node, return false
        return isBalanced(root.left) && isBalanced(root.right);//result determined by whether both left child tree and right child tree are balanced tree
    //get height of every node from node to leaves
    var getHeight = (node) => {
        if(!node) return 0;
        node.height = Math.max(getHeight(node.left), getHeight(node.right)) + 1;
        return node.height;

Log in to reply

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