算法学习

算法题--二叉树单条相连路径元素的最大和

2020-05-04  本文已影响0人  岁月如歌2020
image.png

0. 链接

题目链接

1. 题目

Given a non-empty binary tree, find the maximum path sum.

For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.

Example 1:

Input: [1,2,3]

       1
      / \
     2   3

Output: 6

Example 2:

Input: [-10,9,20,null,null,15,7]

   -10
   / \
  9  20
    /  \
   15   7

Output: 42

2. 思路1: 递归

3. 代码

# coding:utf8


# 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 maxPathSum(self, root: TreeNode) -> int:

        max_value = None

        def check(node):
            nonlocal max_value
            if node is None:
                return 0
            left = max(0, check(node.left))
            right = max(0, check(node.right))
            # 子树要试图成为最大值
            if max_value is not None:
                max_value = max(max_value, left + right + node.val)
            else:
                max_value = left + right + node.val
            # 选择较大的一边, 继续往上寻根
            return max(left, right) + node.val

        check(root)
        return max_value


solution = Solution()

root1 = node = TreeNode(1)
node.left = TreeNode(2)
node.right = TreeNode(3)
print(solution.maxPathSum(root1))

root2 = node = TreeNode(-10)
node.left = TreeNode(9)
node.right = TreeNode(20)
node.right.left = TreeNode(15)
node.right.right = TreeNode(7)
print(solution.maxPathSum(root2))

root3 = node = TreeNode(-3)
print(solution.maxPathSum(root3))

root4 = node = TreeNode(-2)
node.left = TreeNode(-1)
print(solution.maxPathSum(root4))


root5 = node = TreeNode(-1)
node.left = TreeNode(9)
node.right = TreeNode(20)
node.right.left = TreeNode(15)
node.right.right = TreeNode(7)
print(solution.maxPathSum(root5))

输出结果

6
42
-3
-1
43

4. 结果

image.png
上一篇下一篇

猜你喜欢

热点阅读