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. 转 SQL Union和SQL Union All两者用法区别效率以及与order by 和 group by配合问题

    SQL Union和SQL Union All两者用法区别效率以及与order by 和 group by配合问题 SQL Union和SQL Union All用法 SQL UNION 操作符 UN ...

  2. oAuth协议学习

    我们的项目需要为一个认证网站开发一套API,这些API可以提供给很多公司来调用,但是公司在调用之前,必须先做授权认证,由此接触到了oAuth协议. 以下内容来自网络整理 定义 OAUTH协议为用户资源 ...

  3. biztalk中使用WCF-SQL接受传送数据【转】

    接触biztalk时间不长,转载一篇学习教程: http://www.cnblogs.com/chnking/archive/2010/05/09/1731098.html chnking写的. 一. ...

  4. 使用反射来编写实体类的XML

    前言: 开发过程中经常需要返回某实体类的列表,公司通常用的都是XML格式的接口,小猪借鉴了公司前辈留下的代码一直是类似这么写的: public static string GetXMLList(ILi ...

  5. HookIAT的启动程序

    // 启动程序.cpp : 定义控制台应用程序的入口点. // #include "stdafx.h" #include <Windows.h> #include &l ...

  6. 时钟 IoTimer

    /* 例程是在运行在DISPATCH_LEVEL的IRQL级别 例程中不能使用分页内存 另外在函数首部使用 #pragma LOCKEDCODE */ #include "Driver.h& ...

  7. hdu 4619 Warm up 2

    http://acm.hdu.edu.cn/showproblem.php?pid=4619 根据题意可知,每一个方格可能只被一个骨牌覆盖 可能被两个骨牌覆盖 也可能不被覆盖 有一个骨牌覆盖的方格(单 ...

  8. 纯JS省市区三级联动

    代码下载

  9. wp8.1 Study7: ListView 和GridView应用

    对于列表控件,WP8.1常用的是ListView.GridView.ListBox控件.其中前两个是从第三个继承来的. 1.ListView控件 它是展示垂直列表的,如下图所示.它十分适合展示数据. ...

  10. Cocoapods的安装与使用

    一.安装 1.CocoaPods是用Ruby实现的,要想使用它首先需要有Ruby的环境.OS X系统默认已经可以运行Ruby了,因此我们只需执行以下命令: sudo gem install cocoa ...