def longestUnivaluePath(self, root: TreeNode) -> int:
if not root:
return 0
ans = 0
def longr(root):
if not root:
return 0
pl = 0
pr = 0
l = longr(root.left)
r = longr(root.right)
if root.left and root.val == root.left.val:
pl = l + 1
if root.right and root.val == root.right.val:
pr = r + 1
ans = max(ans,pl + pr)
return max(pl,pr)
longr(root)
return ans
问题出在ans没有被reference
需要把function外的实参ans传入function内,应该在实参加上self.ans,形参也得加上self.ans
修改后
def longestUnivaluePath(self, root: TreeNode) -> int:
if not root:
return 0
self.ans = 0
def longr(root):
if not root:
return 0
pl = 0
pr = 0
l = longr(root.left)
r = longr(root.right)
if root.left and root.val == root.left.val:
pl = l + 1
if root.right and root.val == root.right.val:
pr = r + 1
self.ans = max(self.ans,pl + pr)
return max(pl,pr)
longr(root)
return self.ans