代码改变世界

[LeetCode] 124. Binary Tree Maximum Path Sum_ Hard tag: DFS recursive, Divide and conquer

2018-07-18 05:47  Johnson_强生仔仔  阅读(257)  评论(0编辑  收藏  举报

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


这个题目的思路就是用DFS, 然后我们建一个helper function(input: root, 得到从这个root出发的一条path s.t path sum 最大), 得到包括root的最大的path sum,
然后recursive 去看是否包括root.left path sum 和root.right path sum, 这里需要
注意的是, 返回的时候因为是path, 所以left和right只能选一边, 只是self.ans 可以考虑left + right+ root.最后返回self.ans

04/18/2019 update
可以一步一步的来看, 第一步, 考虑 root -> leaf 的maximum sum,利用Divide and conquer
class Solution:
    def maxSum(self, root):
        if not root: return 0
        left = self.maxSum(root.left)
        right = self.maxSum(root.right)
        return root.val + max(left, right)

第二步, 考虑 root -> any node 的maximum sum, 实际上就是基于root -> leaf的情况下,加入了如果children 的maximum sum 是负数的情况,那么就不要加入children的maximum sum。

class Solution:
    def maxSum(self, root):
        if not root: return 0
        left = self.maxSum(root.left)
        right = self.maxSum(root.right)
        return root.val + max(0, left, right)

 

最后考虑any node -> any node的情况, 就可以每个node, 都判断以该点作为root的maximum sum,也就是上面的第二步,只不过设置一个全局变量去将所有点的maximum sum,以及该点加上左,右之后的sum,取最大值,就是我们要的结果。




1. Constraints
1) empty => 0 update:题目说了non-empty,所以不会有。

2. Ideas
DFS T: O(n) S: O(n)

3. Code
 1 class Solution:
 2     def maxSumPath(self, root):
 3         self.ans = None
 4         def rootSum(root):
 5             if not root: return 0
 6             left, right = rootSum(root.left), rootSum(root.right)
 7             localSum = max(root.val, root.val + left, root.val + right)
 8             potentialSum = max(localSum , root.val + left + right)
 9             if self.ans == None or potentialSum > self.ans:
10                 self.ans = potentialSum
11             return localSum
12         if not root: return 0 # since it is non-empty tree, so this is useless
13         rootSum(root)
14         return self.ans

 

4. Test cases

1) empty => 0 , leetcode上面好像这里返回的是Min_value, 一个最小负数, 我觉得应该是0, 不过test cases里面没有加, 所以无所谓  update:题目说了non-empty,所以不会有。

2) -1

3) 

   -10
   / \
  9  20
    /  \
   15   7