FastPrepDiameter of a Binary Tree

Diameter of a Binary Tree

Bloomberg LP logoBloomberg LP● EasyNEW GRADONSITE INTERVIEW
Learn

Problem statement

Given the root of a binary tree, return its diameter: the maximum number of edges on a path between any two nodes.

The path may or may not pass through the root. Return 0 for an empty tree or a one-node tree.

Function

diameterOfBinaryTree(root: TreeNode) → int

Examples

Example 1

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

A longest path is 4 → 2 → 1 → 3, which contains three edges.

Example 2

root = [1,2]return = 1

The only nonempty path between distinct nodes uses one edge.

Example 3

root = []return = 0

An empty tree has no edges.

Constraints

  • The tree contains between 0 and 100000 nodes.
  • -10^9 <= Node.val <= 10^9.
  • Node values do not affect the answer.

More Bloomberg LP problems

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