Tree - 298. Binary Tree Longest Consecutive Sequence

9

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
}