AlgoLounge

Diameter of Binary Tree

easy

LeetCode 543. Diameter of Binary Tree

The diameter of a binary tree is defined as the length of the longest path between any two nodes within the tree. The path does not necessarily have to pass through the root.

The length of a path between two nodes in a binary tree is the number of edges between the nodes. Note that the path cannot include the same node twice.

Given the root of a binary tree root, return the diameter of the tree.

Examples

Example 1

Input:  root = [1,2,3]
Output: 2

The longest path is [2,1,3] with length 2.

Example 2

Input:  root = [1,2]
Output: 1

The longest path is [2,1] with length 1.

Constraints

  • 1 <= number of nodes in the tree <= 100
  • -100 <= Node.val <= 100

How the tests work: trees are written as level-order arrays — [1,null,2] is a root 1 with a right child 2. Your function receives real TreeNode objects.

TypeScript
Loading editor…
List of test cases (10)
Case 1
root = [1,2,3]
Case 2
root = [1,2]
Case 3
root = [1]
Case 4
root = [1,2,3,4,5]
Case 5
root = [1,2,null,4,null,5]
Case 6
root = [1,null,2,null,3,null,4]
Case 7
root = [1,2,3,4,5,6,7]
Case 8
root = [-10,9,20,null,null,15,7]
Case 9
root = [1,2,3,4,5,null,null,6,7]
Case 10
root = [4,-7,-3,null,null,-9,-3,9,-7,-4,null,6,null,-6,-6,null,null,0,6,5,null,9,null,null,-1,-4,null,null,null,-2]