假设我们有一棵二叉树。我们必须找到总和为偶数的最长路径的长度。
因此,如果输入像图像,那么输出将是5,因为路径像[5、2、4、8、5],总和= 24(even)。
让我们看下面的实现以更好地理解-
class TreeNode: def __init__(self, data, left = None, right = None): self.val = data self.left = left self.right = right class Solution: def solve(self, root): def dfs(node): if not node: return 0, float("-inf") left_0, left_1 = dfs(node.left) right_0, right_1 = dfs(node.right) if node.val & 1: self.ans = max(self.ans, left_1 + right_0 + 1, left_0 + right_1 + 1) return max(left_1 + 1, right_1 + 1, 0), max(left_0 + 1, right_0 + 1) else: self.ans = max(self.ans, left_0 + right_0 + 1, left_1 + right_1 + 1) return max(left_0 + 1, right_0 + 1, 0), max(left_1 + 1, right_1 + 1) self.ans = 0 dfs(root) return self.ans ob = Solution() root = TreeNode(2) root.left = TreeNode(5) root.right = TreeNode(4) root.right.left = TreeNode(8) root.right.right = TreeNode(2) root.right.left.left = TreeNode(5) print(ob.solve(root))
root = TreeNode(2) root.left = TreeNode(5) root.right = TreeNode(4) root.right.left = TreeNode(8) root.right.right = TreeNode(2) root.right.left.left = TreeNode(5)输出结果
5