<p>Given the <code>root</code> of a binary tree, return <em>the length of the <strong>diameter</strong> of the tree</em>.</p>

<p>The <strong>diameter</strong> of a binary tree is the <strong>length</strong> of the longest path between any two nodes in a tree. This path may or may not pass through the <code>root</code>.</p>

<p>The <strong>length</strong> of a path between two nodes is represented by the number of edges between them.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/03/06/diamtree.jpg" style="width: 292px; height: 302px;" />
<pre>
<strong>Input:</strong> root = [1,2,3,4,5]
<strong>Output:</strong> 3
<strong>Explanation:</strong> 3 is the length of the path [4,2,1,3] or [5,2,1,3].
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> root = [1,2]
<strong>Output:</strong> 1
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li>
	<li><code>-100 &lt;= Node.val &lt;= 100</code></li>
</ul>

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int diameterOfBinaryTree(TreeNode* root) {
        /*
        the diameter = length of longest path between any two nodes in a tree

        if we consider any node to be the root of a tree, we can calculate the
        diameter at that node to be the maximum depth of the left branch +
        the maximum depth of the right branch. We can calculate the diameter at
        every node and take the maximum diameter.
        */

        int ret = 0;
        helper(root, &ret);

        return ret;
    }

    // ret will keep track of our largest diameter so far
    // root is the node that we are considering the root of the tree
    // function will return largest depth of that node, root, for further
    // diameter calculations up tree.
    int helper(TreeNode* root, int *ret) {
        if (root == NULL) {
            *ret = max(*ret, 0);
            return 0;
        }

        // calculate diameter for sub branch roots.
        int l = helper(root->left, ret);
        int r = helper(root->right, ret);

        *ret = max(*ret, l + r);
        return max(l, r) + 1;
    }
};
22500