Python程序:查找树中所有非相邻节点的最大和


假设我们有一个二叉树,我们需要找到可以获得的最大值之和,前提是不能有两个值是相邻的(父节点和子节点)。

因此,如果输入类似于

则输出将为 17,因为 10、4、3 不相邻。

为了解决这个问题,我们将遵循以下步骤:

  • 定义一个函数 f()。它将接收节点作为参数。
  • 如果节点为空,则
    • 返回 (0, 0)
  • (a, b) := f(节点的左子节点)
  • (c, d) := f(节点的右子节点)
  • 返回一个对 (节点值 + b + d 与 a + c 的最大值, a + c)
  • 从主方法中调用 f(根节点) 并返回其第一个值。

让我们看看以下实现以更好地理解:

示例

 实时演示

class TreeNode:
def __init__(self, data, left = None, right = None):
   self.val = data
   self.left = left
   self.right = right
def f(node):
   if not node:
      return 0, 0
   a, b = f(node.left)
   c, d = f(node.right)
   return max(node.val + b + d, a + c), a + c
class Solution:
   def solve(self, root):
      return f(root)[0]
ob = Solution()
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(10) root.left.left = TreeNode(4) root.left.right = TreeNode(3) print(ob.solve(root))

输入

root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(10)
root.left.left = TreeNode(4)
root.left.right = TreeNode(3)

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

输出

17

更新于: 2020年10月19日

260 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告