FastPrepLongest Consecutive Path in a Binary Tree
Problems/Longest Consecutive Path in a Binary Tree

Longest Consecutive Path in a Binary Tree

Google logoGoogle● MediumNEW GRADPHONE SCREEN
QuestionFunctionExamplesConstraints

Problem statement

Source note: The source reports the increasing parent-to-child path and an any-direction follow-up, but omits the exact combined interface, edge cases, and bounds. The judged core matches the visible source at about 85%.

Given the root of a binary tree and a boolean anyDirection, return the maximum number of nodes in a consecutive path.

When anyDirection is false, the path must follow parent-to-child edges and every next value must equal the previous value plus one.

When anyDirection is true, the path may start and end at any two nodes and may pass from one child through its parent to another child. After choosing one endpoint as the start, every next value along the path must equal the previous value plus one. A node may appear at most once in the path.

Function

longestConsecutivePath(root: TreeNode, anyDirection: boolean) → int

Examples

Example 1

root = [1,null,2,null,3]anyDirection = falsereturn = 3

The parent-to-child path 1 -> 2 -> 3 is consecutively increasing.

Example 2

root = [2,1,3]anyDirection = truereturn = 3

The path may travel from the left child through the root to the right child: 1 -> 2 -> 3.

Example 3

root = [3,2,4,1]anyDirection = falsereturn = 2

The increasing downward path 3 -> 4 has length two. The values 1, 2, 3 are consecutive only when traversed upward, which is not allowed in this mode.

Constraints

  • The tree contains between 1 and 2000 nodes.
  • -1000000000 <= Node.val <= 1000000000.
  • The input is a valid binary tree.

More Google problems

  • Apartment Housemate PreferencesPHONE SCREEN · Seen Nov 2026
  • Price at Query TimestampsPHONE SCREEN · Seen Nov 2026
  • 0/1 Knapsack with Weight and Volume LimitsONSITE INTERVIEW · Seen Nov 2026
All Google interview questionsSee Google hiring insights
Saved
public int longestConsecutivePath(TreeNode root, boolean anyDirection) {
    // write your code here
}
Checking account…