要注意边和节点数是不一样的
# 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]
原文地址:https://www.cnblogs.com/lautsie/p/12244607.html
时间: 2024-10-11 07:17:59