Given the root of a binary tree, return the length of the longest consecutive sequence path.
A consecutive sequence path is a path where the values increase by one along the path.
Note that the path can start at any node in the tree, and you cannot go from a node to its parent in the path.
Example 1:
Input: root = [1,null,3,2,4,null,null,null,5]
Output: 3
Explanation: Longest consecutive sequence path is 3-4-5, so return 3.
Example 2:
Input: root = [2,null,3,2,null,1]
Output: 2
Explanation: Longest consecutive sequence path is 2-3, not 3-2-1, so return 2.
Constraints:
The number of nodes in the tree is in the range [1, 3 * 104].
-3 * 104 <= Node.val <= 3 * 104
Solutions
Solution 1
Thinking
A consecutive path is a downward chain whose values increase by \(1\). Postorder yields the lengths from each child; we extend only when the child is exactly one larger, otherwise restart at \(1\).
\(dfs\) returns the longest consecutive length starting at the current node and updates a global answer.
1 2 3 4 5 6 7 8 910111213141516171819202122232425
# Definition for a binary tree node.# class TreeNode:# def __init__(self, val=0, left=None, right=None):# self.val = val# self.left = left# self.right = rightclassSolution:deflongestConsecutive(self,root:Optional[TreeNode])->int:defdfs(root:Optional[TreeNode])->int:ifrootisNone:return0l=dfs(root.left)+1r=dfs(root.right)+1ifroot.leftandroot.left.val-root.val!=1:l=1ifroot.rightandroot.right.val-root.val!=1:r=1t=max(l,r)nonlocalansans=max(ans,t)returntans=0dfs(root)returnans
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */funclongestConsecutive(root*TreeNode)(ansint){vardfsfunc(*TreeNode)intdfs=func(root*TreeNode)int{ifroot==nil{return0}l:=dfs(root.Left)+1r:=dfs(root.Right)+1ifroot.Left!=nil&&root.Left.Val-root.Val!=1{l=1}ifroot.Right!=nil&&root.Right.Val-root.Val!=1{r=1}t:=max(l,r)ans=max(ans,t)returnt}dfs(root)return}