0

Currently trying to solved Diameter of Binary Tree problem using js. I got a weird code when I do not include const when declaring left/right. Does anyone know why?

var diameterOfBinaryTree = function(root) {
  
  const result = dfs(root, 0);
  return result[1]; 
};
const dfs = (node, diameter) => {
  if(!node)
     return [0, 0];
  
  const left = dfs(node.left, diameter);
  const right = dfs(node.right, diameter);
  let oldDiameter = Math.max(left[1], right[1], diameter);
  let newDiameter = Math.max(oldDiameter, left[0] + right[0]);
  let depth = Math.max(left[0], right[0]) + 1;
  
  return [depth, newDiameter];
}
Sonny
  • 3
  • 1
  • Assigning to an undeclared variable in sloppy mode creates a global variable. You should always use [strict mode](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode) so you don’t have to worry about that. – Ry- Jun 10 '22 at 03:45
  • 1
    what do you means by "got weird code"? – Mario Vernari Jun 10 '22 at 03:45
  • In this case, `left` will be overridden by whatever happens in the `dfs` call for right since `left` would be a global variable – Samathingamajig Jun 10 '22 at 03:49

0 Answers0