Longest Consecutive Path in a Binary Tree
Updated
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.
More Google Phone Screen questions
- Route Pattern MatcherPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Periodic-Color Binary Forest RootsPHONE SCREEN · Seen Nov 2026
- Evaluate a Nested Math ExpressionPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Best Stock Trade with Buy and Sell DaysPHONE SCREEN · Seen Nov 2026
- Word Chain Jumps in a GridPHONE SCREEN · Seen Nov 2026
- Dice-Walk Winning ProbabilityPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Lowest Common Ancestor in an N-ary TreePHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Apartment Housemate PreferencesPHONE SCREEN · Seen Nov 2026
- Price at Query TimestampsPHONE SCREEN · Seen Nov 2026
- Course Schedule Cycle DetectionPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
Similar questions at other companies
- House Robber IIIOkta · PHONE SCREENOkta interview questions
- House Robber IIIGoldman Sachs · PHONE SCREENGoldman Sachs interview questions
- House Robber IIIVisa · PHONE SCREENVisa interview questions
- Maximum Nonadjacent Sum in a General TreeZip · PHONE SCREEN · ONSITE INTERVIEWZip interview questions
- Minimum-Cost Root-to-Leaf Path in an N-ary TreeBloomberg LP · PHONE SCREENBloomberg LP interview questions
- Lowest Common Manager for Employee GroupsAmazon · PHONE SCREEN
- File Encryption Tree OptimizationDatabricks · PHONE SCREEN · ONSITE INTERVIEWDatabricks interview questions
- Maximum Path Sum Between Marked NodesDoorDash · PHONE SCREENDoorDash interview questions
- Transitive Employee Referral CountsRobinhood · ONSITE INTERVIEWRobinhood interview questions
- Best Sum Downward Tree PathCitadel · OACitadel interview questions