298 Binary Tree Longest Consecutive Sequence
Given a binary tree, find the length of the longest consecutive sequence path.
The path refers to any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The longest consecutive path need to be from parent to child (cannot be the reverse).
For example,
Longest consecutive sequence path is 3-4-5, so return 3.
Longest consecutive sequence path is 2-3,not 3-2-1, so return 2.
The Idea: Run a DFS proceedure that maintains the current consequtive distance, and updates the maximum as you go along. If the root is non existant, return 0; otherwise begin with a consequtive distance of 1, and begin the recursive call. If the left or right child's value is 1 more than it's parent, increment the consecutive distance. Otherwise, reset back to 1 - and try again on that new subtree. In the end, we are just running a preorder traversal with a few additional checks.
Complexity: O(n) time and space
Last updated