Javascript: Minimum Depth of Binary Tree, getting error: TypeError: number is not a function


  • 0
    R

    here is my code:

    var minDepth = recursive(root);
        
            function recursive(root)
            {
                if(root==null) return 0;
                return Math.min(recursive(root.right),recursive(root.left))+1;
            }
    

    If I change root==null to root===null it doesn't handle undefined anymore.
    I tried replacing Math.min with a function of my own but it made no difference.

    Code works on my IE and Chrome.


  • 0
    R

    anyone? I tried to make it "fuller" via this added code, but makes no difference.

        var minDepth = recursive(root);
    
        function recursive(root)
        {
            if(root==null) return 0;
            if (root.left==null && root.left==null) return 1;
            if (root.left==null) return recursive(root.right)+1;
            else if (root.right==null) return recursive(root.left)+1;
            return Math.min(recursive(root.right),recursive(root.left))+1;
        }
    

  • 0
    R

    Silly. I had to leave the original code alone. This "works":

    var minDepth = function(root) {
    return recursive(root);
    };

    And by works I mean in leetcode. It does not work in my WebStorm IDE.
    Now it gives me error on usecase.
    What does this input even mean?
    Input: [1,null,2]
    Output: 1
    Expected:2

    Does this mean it creates one TreeNode with Left = 2nd and Right = null?
    And the 2nd is Left = 3rd, Right undefined.


  • 0
    R

    Silly. I had to leave the original code alone. This "works":

    var minDepth = function(root) {
        return recursive(root);
    };
    

    Basically leetcode requires to call minDepth(). minDepth cannot be the result, it has to be the function name.


  • 1
    R

    Final accepted solution:

    var minDepth = function(root) {
                if(root==null) return 0;
                if (root.left==null) return minDepth(root.right)+1;
                if (root.right==null) return minDepth(root.left)+1;
                return Math.min(minDepth(root.right),minDepth(root.left))+1;
    };
    

Log in to reply
 

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