Tree - 687. Longest Univalue Path

时间:2022-07-25
本文章向大家介绍Tree - 687. Longest Univalue Path,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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:

              5
             / 
            4   5
           /    
          1   1   5

Output: 2

Example 2:

Input:

              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:

/**

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

随机文章