前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Tree - 298. Binary Tree Longest Consecutive Sequence

Tree - 298. Binary Tree Longest Consecutive Sequence

作者头像
ppxai
发布2020-09-23 17:31:24
2700
发布2020-09-23 17:31:24
举报
文章被收录于专栏:皮皮星球皮皮星球

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:

代码语言:javascript
复制
Input:
   1
    \
     3
    / \
   2   4
        \
         5
Output:3
Explanation:
Longest consecutive sequence path is 3-4-5, so return 3.

思路:

找出根到叶子节点的路径中的最长递增序列,做法就是由根节点向叶子节点探索的过程中,比较父节点与子节点的大小关系,更新结果最大值即可。

代码:

go:

代码语言:javascript
复制
/**
 * 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
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019年08月19日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档