Leetcode - Binary Tree Maximum Path Sum
Leetcode - Add One Row to Tree

Leetcode - Longest Univalue Path

violet posted @ Apr 30, 2020 06:09:45 AM in 算法 with tags Algorithm Golang tree , 166 阅读

https://leetcode.com/problems/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

 

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func longestUnivaluePath(root *TreeNode) int {
    maxNum := 0
    find(root, &maxNum)
    return maxNum
}

func find(root *TreeNode, maxNum *int) int {
    if root == nil {
        return 0
    }
    left := find(root.Left, maxNum)
    right := find(root.Right, maxNum)
    l := 0
    r := 0
    if root.Left != nil && root.Left.Val == root.Val {
        l = left + 1
    }
    if root.Right != nil && root.Right.Val == root.Val {
        r = right + 1
    }
    *maxNum = max(*maxNum, l + r)
    
    return max(l, r)
}

func max(a, b int) int {
    if a > b {
        return a
    }
    
    return b
}

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter