<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.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:
        # for each node, find max diameter from that node
        queue = [root]
        max_diam = 0
        while queue:
            node = queue.pop(0)

            max_diam =  max(max_diam, (self.max_depth(node.left) + self.max_depth(node.right)))

            if node.left:
                queue.append(node.left)
            if node.right:
                queue.append(node.right)

        return max_diam
    
    # def max_diameter(self, node: Optional[TreeNode]) -> int:
    #     left_max, right_max = 0, 0
    #     if node.left:
    #         left_max = self.max_depth(node.left)
    #     if node.right:
    #         right_max = self.max_depth(node.right)

    #     return left_max + right_max        

    def max_depth(self, node: Optional[TreeNode]) -> int:
        if not node: 
            return 0

        stack = [(node, 1)]
        max_val = 0

        while stack:
            node, node_val = stack.pop()
            
            max_val = max(max_val, node_val)
            if node.left:
                stack.append((node.left, node_val + 1))
            if node.right:
                stack.append((node.right, node_val + 1)) 

        return max_val


17800