Longest Consecutive Path in a Binary Tree
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) → intExamples
Example 1
root = [1,null,2,null,3]anyDirection = falsereturn = 3The parent-to-child path 1 -> 2 -> 3 is consecutively increasing.
Example 2
root = [2,1,3]anyDirection = truereturn = 3The 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 = 2The 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
1and2000nodes. -1000000000 <= Node.val <= 1000000000.- The input is a valid binary tree.