EasyTreeDepth-First SearchBinary Tree

1 approach, code in every language

Problem description

You are given the root of a binary tree. The diameter is defined as the length of the longest path between any two nodes in the tree, measured by the number of edges on that path.

The path does not need to run through the root, and the two endpoints can be any pair of nodes. Return the diameter of the tree.

Example 1

Input: root = [1,2,3,4,5]

Output: 3

The longest path is 4 -> 2 -> 1 -> 3 (or 5 -> 2 -> 1 -> 3), which contains 3 edges.

Example 2

Input: root = [1,2]

Output: 1

The only path connecting two nodes is 1 -> 2, a single edge.

Constraints

  • The number of nodes in the tree is in the range [1, 10^4].
  • -100 <= Node.val <= 100

After the pattern

Now solve one you haven't seen.

Widest Gallery Walk is our own problem on the technique behind Diameter of Binary Tree: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free