title: Refactoring C function to find diameter of Binary Tree in O(n) to JavaScript
body: <p>I'm having trouble understanding/re-writing the "optimized" C function given <a href="http://www.geeksforgeeks.org/diameter-of-a-binary-tree/" rel="nofollow">here</a> for find the diameter of a binary tree. I dont understand how its keeping track of the height. I get that its using the second parameter height to accomplish this, but in the code I dont even see the height parameter being used. I have trouble understanding functions in C, I primarily write in JavaScript. I was able to re-write all of the other functions on the page though without issue.</p>
  
  <pre><code>/*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, &amp;height); */
  int diameterOpt(struct node *root, int* height)
  {
    /* lh --&gt; Height of left subtree
        rh --&gt; Height of right subtree */
    int lh = 0, rh = 0;
  
    /* ldiameter  --&gt; diameter of left subtree
        rdiameter  --&gt; 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-&gt;left, &amp;lh);
    rdiameter = diameterOpt(root-&gt;right, &amp;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));
  }
  </code></pre>