Diameter of Binary Tree
Given the root of a binary tree represented as an array in level-order, return the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root. The length of a path between two nodes is represented by the number of edges between them. **Examples:** ```typescript diameterOfBinaryTree([1, 2, 3, 4, 5]) // 3 (path [4,2,1,3] or [5,2,1,3]) diameterOfBinaryTree([1, 2]) // 1 ```
Solve It in the BrowserPractice Explaining It Out Loud
Optimal Approach
- Time complexity: O(n)
- Space complexity: O(h)
Each node in the tree is visited once to compute its depth and update maximum path length.
Follow-Up Questions Interviewers Ask About Diameter of Binary Tree
- Does the diameter path necessarily pass through the tree root?
No. The longest path can exist entirely within a subtree if one branch is much deeper than the other.
Practice the full problem with execution, tests, and AI code review in the interactive lab — then rehearse explaining your solution in a live voice mock interview.