我正在解决leetcode问题1372。为什么这两个代码返回不同的结果?第一个给出了正确答案。第二个没有。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def __init__(self):
self.longest_path = 0
def longestZigZag(self, root: Optional[TreeNode]) -> int:
val1 = 1 + self.helper(root.right, 'r')
val2 = 1 + self.helper(root.left, 'l')
# print(val2, self.longest_path)
val = max(val1, val2)
return max(val, self.longest_path) - 1
def helper(self, root, d):
if root == None:
return 0
if d == 'l':
l_path = 1 + self.helper(root.left, d='l')
self.longest_path = max(self.longest_path, l_path)
return 1 + self.helper(root.right, d='r')
if d == 'r':
r_path = 1 + self.helper(root.right, d='r')
self.longest_path = max(self.longest_path, r_path)
return 1 + self.helper(root.left, d='l')
class Solution:
def __init__(self):
self.longest_path = 0
def longestZigZag(self, root: Optional[TreeNode]) -> int:
val1 = 1 + self.helper(root.right, 'r')
val2 = 1 + self.helper(root.left, 'l')
# print(val2, self.longest_path)
val = max(val1, val2)
return max(val, self.longest_path) - 1
def helper(self, root, d):
if root == None:
return 0
if d == 'l':
self.longest_path = max(self.longest_path, 1 + self.helper(root.left, d='l'))
return 1 + self.helper(root.right, d='r')
if d == 'r':
r_path = 1 + self.helper(root.right, d='r')
self.longest_path = max(self.longest_path, r_path)
return 1 + self.helper(root.left, d='l')
唯一的变化是这一行:
“self.longest_path = max(self.longest_path, 1 + self.helper(root.left, d='l'))”
第二个代码丢失了
l_path = 1 + self.helper(root.left, d='l')
。