All problems

Problem 923

Binary Tree Longest Consecutive Sequence

Medium · 20 pts · Tree, Depth-First Search

Problem

Find the length of the longest consecutive sequence path in a binary tree: a downward path from a parent to a child where each value is exactly one more than the value before it (like 3, 4, 5). The path can start at any node, and its length is its number of nodes. Pass the current run length down the tree: a child continues the run if its value is the parent's value plus one, and otherwise starts a new run of length 1.

Input

The first line contains N, the number of tokens. The second line contains N tokens describing the tree in level order (breadth-first, left to right), where 'null' marks a missing child, as on LeetCode.

Output

Print the length of the longest consecutive path.

Constraints

1 <= number of nodes <= 30000; -30000 <= value <= 30000

Example input

9
1 null 3 2 4 null null null 5

Example output

3

Explanation

In 1 null 3 2 4 null null null 5, the path 3 → 4 → 5 increases by one at each step and has 3 nodes, the longest such path.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Binary Tree Coloring Game Next: Height of Binary Tree After Subtree Removal Queries