687. Longest Univalue Path

Posted johnnyzhao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了687. Longest Univalue Path相关的知识,希望对你有一定的参考价值。

/**
 * 687. Longest Univalue Path(最长的相同值路经)
 * https://leetcode.com/problems/longest-univalue-path/description/
 * https://www.youtube.com/watch?v=yX1hVhcHcH8
 * */
class TreeNode(var `val`: Int) {
    var left: TreeNode? = null
    var right: TreeNode? = null
}

class Solution {
    var result = 0
    fun longestUnivaluePath(root: TreeNode?): Int {
        if (root == null) {
            return 0
        }
        helper(root)
        return result
    }

    private fun helper(root: TreeNode?): Int {
        if (root == null) {
            return 0
        }
        //求出单边的univaluePath
        val l = helper(root.left)
        val r = helper(root.right)
        var pl = 0
        var pr = 0
        if (root.left != null && root.`val` == root.left?.`val`) {
            pl = l + 1
        }
        if (root.right != null && root.`val` == root.right?.`val`) {
            pr = r + 1
        }
        result = Math.max(result, pl + pr)
        //返回单边最大的
        return Math.max(pl, pr)
    }
}

以上是关于687. Longest Univalue Path的主要内容,如果未能解决你的问题,请参考以下文章

[leetcode-687-Longest Univalue Path]

[LeetCode] 687. Longest Univalue Path

Recursion-687. Longest Univalue Path

687. Longest Univalue Path

687. Longest Univalue Path 最长的唯一路径

687. Longest Univalue Path 687.最长单值路径