Tree - 298. Binary Tree Longest Consecutive Sequence

Published on with 0 views and 0 comments

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
}
``````