Problem Link:

http://oj.leetcode.com/problems/binary-tree-maximum-path-sum/

For any path P in a binary tree, there must exists a node N in P such that N is the ancestor node of all other nodes in P. We call such N as the root of P, or P roots at N.

Then we know that any maximum sum path must root at some node in the tree. Therefore, the naive method to solve this problem is to check all paths root at each node in the tree, and return the maximum path sum.

We can solve this problem efficiently in the help of the function that can find the maximum sum path from the node to any nodes in its sub-tree.

Let P = {N1, ..., Nn, N, M1, ..., Mm} be a maximum path rooting at N, where n and m both could be 0. Then {N1, ..., Nn, N} would be the maximum path from N to any nodes in N's left sub-tree, and {N, M1, ..., Mm} must be the maximum path from N to any nodes in N's right sub-tree. Therefore, we can traverse the tree in post-order, and for each node N we compute the maximum path rooting at N and update it with a global variable. The recursive algorithm can go as follows.

MAX-PATH-SUM-RECURSIVE(node N):
  if N is NULL:
    return 0
  // Compute the maximum path sum of N's children recursively
  l_max_path_sum = MAX-PATH-SUM-RECURSIVE(N.left)
  r_max_path_sum = MAX-PATH-SUM-RECURSIVE(N.right)
  // Compute the maximum path rooting at N
  my_max_sum = N.val
  if l_max_path_sum > 0 then
    my_max_sum += l_max_path_sum
  if r_max_path_sum > 0 then
    my_max_sum += r_max_path_sum
  // Compare with the global variable
  if my_max_sum > CURRENT_MAX_SUM:
    CURRENT_MAX_SUM = my_max_sum
  // Return the maximum path sum from N to nodes in N's sub-tree
  return max(N.val, N.val + l_max_path_sum, N.val + r_max_path_sum)

So we call the recursive function from tree root, the function would compute maximum path sum starting from each node. At the same time, we maintian the global CURRENT_MAX_SUM which stores the maximum path sum. When the post-order traversal from the root is done, we return CURRENT_MAX_SUM.

class Solution:
# @param root, a tree node
# @return an integer
def maxPathSum(self, root):
"""
For any max path P of the tree, there must exist a node N in P,
such that N is the ancestor node of all other nodes in P.
Let P = {N_1, ..., N_n, N, M_1, ..., M_m}, n and m could be 0.
Then we know that {N_1, ..., N_n, N} is the maximum path from N to nodes in its left sub-tree,
and {N, M_1, ..., M_m} is the maximum path from N to nodes in its right sub-tree.
Therefore, we can run the recursive function that finds the maximum path from N to nodes in its sub-tree,
and use a global variable to store the sum of max path P for each N. @param root: a binary tree node
@return: the maximum path sum of the tree
"""
self.res = 0
if root:
self.res = root.val
self.maxPathSum_recursive(root)
return self.res def maxPathSum_recursive(self, node):
"""
Find the maximum path sum of all paths from node to any nodes in its sub-tree
The recursive function works as follows:
1. If the node is None, return 0
2. Let L be the maximum sum of node.left
3. Let R be the maximum sum of node.right
4. return max(node.val, node.val + L, node.val + R) @param node: a binary tree node
@return: the maximum path sum from node to any node in its sub-tree
"""
if node is None:
return 0
else:
# Compute the left max path sum
left_max = self.maxPathSum_recursive(node.left)
# Compute the left max path sum
right_max = self.maxPathSum_recursive(node.right)
# Update the result with the max path sum rooted at node
max_sum_passing_node = node.val
if left_max > 0:
max_sum_passing_node += left_max
if right_max > 0:
max_sum_passing_node += right_max
self.res = max(self.res, max_sum_passing_node)
# Return the max path sum from this node
return max(node.val, node.val+left_max, node.val+right_max)

【LeetCode OJ】Binary Tree Maximum Path Sum的更多相关文章

  1. LeetCode OJ:Binary Tree Maximum Path Sum(二叉树最大路径和)

    Given a binary tree, find the maximum path sum. For this problem, a path is defined as any sequence ...

  2. 【leetcode】Binary Tree Maximum Path Sum

    Binary Tree Maximum Path Sum Given a binary tree, find the maximum path sum. The path may start and ...

  3. 【leetcode】Binary Tree Maximum Path Sum (medium)

    Given a binary tree, find the maximum path sum. The path may start and end at any node in the tree. ...

  4. 【LEETCODE OJ】Binary Tree Postorder Traversal

    Problem Link: http://oj.leetcode.com/problems/binary-tree-postorder-traversal/ The post-order-traver ...

  5. Leetcode solution 124: Binary Tree Maximum Path Sum

    Problem Statement Given a non-empty binary tree, find the maximum path sum. For this problem, a path ...

  6. 【LeetCode OJ】Binary Tree Level Order Traversal

    Problem Link: https://oj.leetcode.com/problems/binary-tree-level-order-traversal/ Traverse the tree ...

  7. 【LeetCode OJ】Binary Tree Zigzag Level Order Traversal

    Problem Link: https://oj.leetcode.com/problems/binary-tree-zigzag-level-order-traversal/ Just BFS fr ...

  8. 【LeetCode OJ】Binary Tree Level Order Traversal II

    Problem Link: https://oj.leetcode.com/problems/binary-tree-level-order-traversal-ii/ Use BFS from th ...

  9. 【LEETCODE OJ】Binary Tree Preorder Traversal

    Problem Link: http://oj.leetcode.com/problems/binary-tree-preorder-traversal/ Even iterative solutio ...

随机推荐

  1. python中字典dict的操作

    字典可存储任意类型的对象,由键和值(key - value)组成.字典也叫关联数组或哈希表. dict = {' , 'C' : [1 , 2 , 3] } dict['A'] = 007 # 修改字 ...

  2. jsp-------------之分页技术(一)

    jsp分页技术之: 如下图:百度的喵 看上图中卡哇伊的小苗的爪子下面的数字,就是分页啦!那我们如何做出这样一个效果呢? 下面我们来逐一分解: jsp分页技术一 :  (算法) /* int pageS ...

  3. C++文件读写练习

    编写一个程序,统计data.txt文件的行数,并将所有行前加上行号后写到data1.txt文件中. 算法提示: 行与行之间以回车符分隔,而getline()函数以回车符作为终止符.因此,可以采用get ...

  4. Objective-C(一简介)

    Objective-C简介 通常写作ObjC和较少用的Objective C或Obj-C,是扩充C的面向对象编程语言.它主要使用于Mac OS X和GNUstep这两个使用OpenStep标准的系统, ...

  5. WCF练习小程序总结

    1.什么是WCF 严格的说,WCF就是专门用于服务定制.发布与运行以及消息传递和处理的一组专门类的集合,也就是所谓的“类库”.这些类通过一定方式被组织起来,共同协 作,并为开发者提供了一个统一的编程模 ...

  6. spring 标注

    1.添加支持标注的spring中的jar包: spring-context.jar spring-context-support.jar 2.在xml中配置命名空间和schema <beans ...

  7. ASP.NET MVC统一异常处理

    前言: 今早看了篇文章:求知成瘾,却无作品 的思考:很有感触,发现原来自己也是这样,对每样东西都抱有很大的兴趣或者希望自己去学,一年后发现原来自己什么都是皮毛什么都不精!最终发现真正的大牛都是在某一个 ...

  8. android程序打包成APK

    1.下载ant(从官网上下载没有bin目录,可以直接在百度上搜APACHE-ANT-1.9.4-BIN.ZIP) 2.解压到C盘根目录(也可以是其他盘) 3.修改环境变量 ANT_HOME    C: ...

  9. bzoj 3687 bitset的运用

    题目大意: 小呆开始研究集合论了,他提出了关于一个数集四个问题:1. 子集的异或和的算术和.2. 子集的异或和的异或和.3. 子集的算术和的算术和.4. 子集的算术和的异或和.目前为止,小呆已经解决了 ...

  10. 【转发】RedHat Enterprise Linux 6.4 使用 Centos 6 的yum源问题

    作为一名新手,学习Linux已经一个月了,其间遇到了不少问题,而今天笔者遇到的问题是 #yum install pam-devel #This system is not registered to ...