0

Binary Tree Longest Consecutive Sequence

Problem statement:

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:

Longest Consecutive

 

Logic:

For each node we need to check if next node has a value equal to currentNode.value+1 because as per constraint only increasing order is allowed. If yes, increment count, else for that node number of elements in sequence will be 1. Before returning function call maxLength will store maximum number of elements in sequence till now. Recursively call this function for each child of node.

Code: