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

Tree - 687. Longest Univalue Path

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

687. Longest Univalue Path

Given a binary tree, find the length of the longest path where each node in the path has the same value. This path may or may not pass through the root.

The length of path between two nodes is represented by the number of edges between them.

Example 1:

Input:

代码语言:javascript
复制
              5
             / \
            4   5
           / \   \
          1   1   5

Output: 2

Example 2:

Input:

代码语言:javascript
复制
              1
             / \
            4   5
           / \   \
          4   4   5

Output: 2

Note: The given binary tree has not more than 10000 nodes. The height of the tree is not more than 1000.

思路:

题目意思是找出一个二叉树中值相同的路径的种数,树是天然的递归结构,所以题目几乎都可以用递归求解,仔细思考可以发现,对于任意一个节点,对父级节点,只有两种返回结果,一种是自己的和其中一个孩子节点值相同,向上返回对应的长度,一种是自己和两个子节点相同,那么像外层也就是父级节点返回的就是0,因为不允许路径交叉。所以可以看做一个后序遍历求解。

代码:

go:

代码语言:javascript
复制
/**

 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func longestUnivaluePath(root *TreeNode) int {
    if root == nil {
        return 0
    }
    
    var res int
    univaluePath(root, &res)
    
    return res
}

func univaluePath(node *TreeNode, res *int) int {
    if node == nil {
        return 0
    }
    
    leftLen := univaluePath(node.Left, res)
    rightLen := univaluePath(node.Right, res)

    var leftPathLen, rightPathLen int
    if node.Left != nil && node.Val == node.Left.Val {
       leftPathLen = leftLen + 1
    }
    if node.Right != nil && node.Val == node.Right.Val {
      rightPathLen = rightLen + 1
    }
    
    *res = max(*res, leftPathLen + rightPathLen)
    
    return max(leftPathLen, rightPathLen)
    
}

func max(i, j int) int {
    if i > j {
        return i
    }
    
    return j
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019年12月10日,如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

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