[leetcode]Longest Univalue Path
Posted 阿牧遥
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[leetcode]Longest Univalue Path相关的知识,希望对你有一定的参考价值。
要注意边和节点数是不一样的
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def longestUnivaluePath(self, root: TreeNode) -> int: result = [0] def backtrace(node, result): if not node: return 0 leftPathMax = backtrace(node.left, result) rightPathMax = backtrace(node.right, result) ret = 0 if node.left and node.val == node.left.val: ret = max(ret, leftPathMax + 1) result[0] = max(result[0], ret) if node.right and node.val == node.right.val: ret = max(ret, rightPathMax + 1) result[0] = max(result[0], ret) if node.left and node.right and node.val == node.left.val and node.val == node.right.val: result[0] = max(result[0], leftPathMax + rightPathMax + 2) return ret backtrace(root, result) return result[0]
以上是关于[leetcode]Longest Univalue Path的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode409. Longest Palindrome
[Leetcode]Longest Palindromic Substring
leetcode longest consecutive sequence