FastPrepLongest Consecutive Path in a Binary Tree

Longest Consecutive Path in a Binary Tree

Google logoGoogle● MediumNEW GRADPHONE SCREEN
Learn

Problem statement

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

See Google hiring insights
public int longestConsecutivePath(TreeNode root, boolean anyDirection) {
    // write your code here
}
root[1,null,2,null,3]
anyDirectionfalse
expected3
Checking account…