重构 C 函数以在 O(n) 到 JavaScript 中找到二叉树的直径

Refactoring C function to find diameter of Binary Tree in O(n) to JavaScript

我在 understanding/re-writing "optimized" C 函数 here 中遇到问题,该函数用于查找二叉树的直径。我不明白它是如何跟踪高度的。我知道它使用第二个参数 height 来完成此操作,但在代码中我什至没有看到正在使用的 height 参数。我很难理解 C 中的函数,我主要用 JavaScript 编写。我能够重写页面上的所有其他功能,但没有问题。

/*The second parameter is to store the height of tree.
   Initially, we need to pass a pointer to a location with value
   as 0. So, function should be used as follows:

   int height = 0;
   struct node *root = SomeFunctionToMakeTree();
   int diameter = diameterOpt(root, &height); */
int diameterOpt(struct node *root, int* height)
{
  /* lh --> Height of left subtree
      rh --> Height of right subtree */
  int lh = 0, rh = 0;

  /* ldiameter  --> diameter of left subtree
      rdiameter  --> Diameter of right subtree */
  int ldiameter = 0, rdiameter = 0;

  if(root == NULL)
  {
    *height = 0;
     return 0; /* diameter is also 0 */
  }

  /* Get the heights of left and right subtrees in lh and rh
    And store the returned values in ldiameter and ldiameter */
  ldiameter = diameterOpt(root->left, &lh);
  rdiameter = diameterOpt(root->right, &rh);

  /* Height of current node is max of heights of left and
     right subtrees plus 1*/
  *height = max(lh, rh) + 1;

  return max(lh + rh + 1, max(ldiameter, rdiameter));
}

近似相当于通过引用传递(在您提供的示例中有很好的评论)将是 属性 的对象:

var heightHolder = { height:0};
var diam = diameterOpt(root, heightHolder);
console.log(heightHolder.height);

function diameterOpt(root, heightHolder){
   if (!root)  {
      heightHolder.height = 0; 
      return 0;
   }
   var refLh = {height:0};
   var refRh = {height:0};
   var ldiameter = diameterOpt(root.left, refLh); 
   ....
   heightHolder.height = Math.max(refLh.height, refRh.height) + 1;
   return ...
}

通常你不会走这样疯狂的路线,因为 JavaScript 支持以更自然的方式返回多个值:

 function diameterOpt(root){
    if (!root){
       return {height:0, diameter:0};
    }
    var leftResult = diameterOpt(root.left);
    var rightResult = diameterOpt(root.right);

    return {
       height:  Math.max(leftResult.height,rightResult.height) + 1;
       diameter: 
           Math.max(leftResult.height+rightResult.height + 1,
                    Math.max(leftResult.diameter, rightResult.diameter))
       }  
}