# Why doesn't it work with JavaScript?

• This is my code with JS:

``````var max=0;
var diameterOfBinaryTree = function(root) {
maxDepth(root);
return max;
};

function maxDepth(node){
if(node === null)
return 0;
else{
var left = maxDepth(node.left);
var right = maxDepth(node.right);
max = Math.max(max,left+right) ;
return Math.max(left,right)+1;
}
}
``````

And then I get WA, the details are:

``````Input:
[]
Output:
3
Expected:
0
``````

I don't know why. And find the topic about it on https://discuss.leetcode.com/topic/83456/java-solution-maxdepth/10:

To understand this problem, you need to know how LeetCode judge call your program and what the static keyword mean.
When you click Run Code / Submit, LeetCode judge will first create an instance of your Solution class i.e. Solution s = new Solution() then call the specific function, s.diameterOfBinaryTree() in this case, and pass in one test case each time. s will be destroyed / GCed after the run. The difference is Run Code only has one test case to test but Submit will repeat those steps for every test case.
The static keyword will make the variable max not be initialized across different test cases. Meaning when the 2nd test case starts, max will still have the value at the end of 1st test case. As you can see when it is failed:
Input:
[]
Output:
3
Expected:
0
It is obvious that max = 3 at the end of the previous test case of [].

So I try to use object max={'val':0} rather than the global variable max=0;

The code is:

``````var diameterOfBinaryTree = function(root) {
var max={'val':0};
maxDepth(root,max);
return max.val;
};

function maxDepth(node,max){
if(node === null)
return 0;
else{
var left = maxDepth(node.left,max.val);
var right = maxDepth(node.right,max.val);
max.val = Math.max(max.val,left+right) ;

return Math.max(left,right)+1;
}
}
``````

But I encounter the problem:Runtime Error

Line 11: TypeError: Cannot read property 'val' of undefined

It can work locally but wrong on the leetcode. It's so confusing.

• I had the same issue. I submitted my solution it says when the input was [], my out put was 3, which does not make any sense. I guess your suspicion about global variable is right. So I changed my code to the following, and it passed.

``````var diameterOfBinaryTree = function(root) {
var max = 0;
var helper = function(root){
if (root===null) return 0

var left = helper(root.left);
var right = helper(root.right);

max = Math.max(max, left + right);

return Math.max(left, right) + 1;
}
helper(root);
return max
}
``````

• It's good solution which use the Closure and is accepted.
However, I still don't know why the old code is wrong.

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