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:
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
public int longestConsecutive(TreeNode root) { if(root == null) return 0; int count = 1; int maxLength = 1; maxLength = longestConsecutive(root,count,maxLength,root.val+1); return maxLength; } int longestConsecutive(TreeNode root, int count,int maxLength,int target) { if(root == null ) return maxLength; if(root.val == target) count++; else count = 1; maxLength = Math.max(maxLength,count); maxLength = longestConsecutive(root.left,count,maxLength,root.val+1); return longestConsecutive(root.right,count,maxLength,root.val+1); } |