# 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).

Example 1:

   1
    \
     3
    / \
   2   4
        \
         5
Longest consecutive sequence path is 3-4-5, so return 3.

Example 2:

   2
    \
     3
    / 
   2    
  / 
 1
Longest consecutive sequence path is 2-3, not 3-2-1, so return 2.

# Solution

Approach 1: recursive.

Approach 2: iterative -- either DFS or BFS is fine.

# Code (Python)

Approach 1:

  def longest_increasing(self, root):
    return self._helper(root, None, 0)
  
  def _helper(self, node, parent, increasing_nodes):
    if not node:
      return increasing_nodes
    if parent and node.val == parent.val + 1:
      new_increasing_nodes = increasing_nodes + 1
    else:
      new_increasing_nodes = 1
    return max(
      new_increasing_nodes,
      self._helper(node.left, node, new_increasing_nodes),
      self._helper(node.right, node, new_increasing_nodes)
    )

Approach 2:

  def longest_increasing(self, root):
    if not root:
      return 0
    result = 1
    stack = [(root, 1, float('inf'))]
    while stack:
      node, longest_so_far, parent_val = stack.pop()
      result = max(result, longest_so_far)
      for child in (node.left, node.right):
        if child:
          if child.val == node.val + 1:
            stack.append((child, longest_so_far + 1, node.val))
          else:
            stack.append((child, 1, node.val))
    return result

# Code (C++)

Approach 1:

Approach 2: