Diameter of a binary tree
Easytreedfsrecursion
The diameter is the number of edges (not nodes) on the longest path between any two nodes. The path may not pass through the root.
Examples write a tree level by level, with null for a missing child: [3,9,20,null,null,15,7].
Example 1
Input: root = [1,2,3,4,5] Output: 3
The path 4 → 2 → 1 → 3 has 3 edges.
Example 2
Input: root = [1,2] Output: 1
Constraints
- 1 ≤ number of nodes ≤ 10⁴
- -100 ≤ Node.val ≤ 100
Submit checks your solution against 7 tests, including hidden ones.
// Provided by the judge: keep these definitions
class TreeNode {
constructor(val = 0, left = null, right = null) {
this.val = val
this.left = left
this.right = right
}
}
/**
* @param {TreeNode|null} root
* @return {int}
*/
function diameterOfBinaryTree(root) {
}