# Tree - 298. Binary Tree Longest Consecutive Sequence

298 . Binary Tree Longest Consecutive Sequence

Description

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:

```Input:
1
\
3
/ \
2   4
\
5
Output:3
Explanation:
Longest consecutive sequence path is 3-4-5, so return 3.```

go：

```/**
* Definition for a binary tree node.
* type TreeNode struct {
*     Val int
*     Left *TreeNode
*     Right *TreeNode
* }
*/

/**
* @param root: the root of binary tree
* @return: the length of the longest consecutive sequence path
*/
func longestConsecutive (root *TreeNode) int {
var res int
if root == nil {
return res
}

recursive(root, 1, &res)

return res
}

func recursive(node *TreeNode, tempRes int, res *int) {
if node.Left == nil && node.Right == nil {
*res = max(*res, tempRes)
return
}

if node.Left != nil {
left := tempRes
if node.Left.Val == node.Val + 1 {
left++
*res = max(*res, left)
} else{
left = 1
}
recursive(node.Left, left, res)
}

if node.Right != nil {
right := tempRes
if node.Right.Val == node.Val + 1 {
right++
*res = max(*res, right)
} else {
right = 1
}
recursive(node.Right, right, res)
}
}

func max(i, j int) int {
if i > j {
return i
}
return j
}```

0 条评论

• ### Tree - 687. Longest Univalue Path

Given a binary tree, find the length of the longest path where each node in the ...

• ### Array - 238. Product of Array Except Self

Given an array nums of n integers where n > 1,  return an array output such that...

• ### Array - 239. Sliding Window Maximum

Given an array nums, there is a sliding window of size k which is moving from th...

• ### Tree - 687. Longest Univalue Path

Given a binary tree, find the length of the longest path where each node in the ...

• ### 2017 Multi-University Training Contest - Team 9 1001&&HDU 6161 Big binary tree【树形dp+hash】

Big binary tree Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/65...

• ### Array - 238. Product of Array Except Self

Given an array nums of n integers where n > 1,  return an array output such that...

• ### POJ 刷题系列：2965. The Pilots Brothers' refrigerator

POJ 刷题系列：2965. The Pilots Brothers’ refrigerator 传送门：POJ 2965. The Pilots Brothe...

• ### 前缀和--详讲

T组数据，每组有N个数，然后给出R,L。目标是让你求出在区间[R,L]之间的和。（0<= R < L <=N）。

• ### 1042 字符统计 (20 分)

版权声明：本文为博主原创文章，遵循 CC 4.0 BY-SA 版权协议，转载请附上原文出处链接和本声明。