FastPrepDiameter of a Binary Tree

Diameter of a Binary Tree

Meta logoMeta● EasyFULLTIMEONSITE INTERVIEW
Learn

Problem statement

Given the root of a binary tree, return its diameter: the largest number of edges on a path between any two nodes. The path may pass through the root, but does not have to.

Function

diameterOfBinaryTree(root: TreeNode) → int

Examples

Example 1

root = [1,2,3,4,5]return = 3

The path from node 4 through nodes 2 and 1 to node 3 has three edges.

Example 2

root = [1,2]return = 1

The only path between the two nodes uses one edge.

Example 3

root = [7]return = 0

A one-node tree has no edge.

Example 4

root = [1,2,3,4,null,null,5,6]return = 5

The longest path runs from node 6 through nodes 4, 2, 1, and 3 to node 5.

Constraints

  • The tree contains between 1 and 10000 nodes.
  • Each node value is an integer between -100 and 100.

More Meta problems

See Meta hiring insights
public int diameterOfBinaryTree(TreeNode root) {
    // Write your code here.
}
root[1,2,3,4,5]
expected3
Checking account…