Ctrl K

Step-by-One Tree Path

Medium
You are given the root of a binary tree holding integers. A path is a chain of distinct nodes where neighbours in the chain are joined by a tree edge; a path may climb to a parent and then go down into another branch. A path qualifies if the values along it change by exactly 1 at each step, always in the same direction: for example 3, 4, 5, 6 or 9, 8, 7. Return the number of nodes on the longest qualifying path. A single node is a path of length 1.
Example 1
root=tree_node([5, 4, 6, 3, None, None, 9]) → 4

The path 3 → 4 → 5 → 6 climbs from the left grandchild to the root and goes down into the right child, each step changing the value by 1. The 9 cannot join it.

Example 2
root=tree_node([2, 3, 3]) → 2

The path 3 → 2 → 3 does not count, since the values must keep moving in one direction. The best is 2 with one of the 3s.

Example 3
root=tree_node([8, 7, None, 6, None, None, 5]) → 4
Constraints
  • 1 ≤ number of nodes ≤ 3·10⁴
  • -3·10⁴ ≤ Node.val ≤ 3·10⁴
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsIs It a Search Tree? MediumTwo Mixed-Up Nodes MediumAll Leaf Paths With a Given Total MediumTree Into a Right Chain MediumDigit Branch Totals Medium
loading Python…
Input
root=tree_node([5, 4, 6, 3, None, None, 9])
Expected
4

Run checks the first 3 tests in your browser. Submit checks all 115 tests on the server, hidden ones included.