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. IO流--字符流

    import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java ...

  2. SAP BDC说明

    简单说一下这个DBC,之前也一直在用,每次找记录都很麻烦,所以今天干脆就记下来吧 T-CODE:SHDB 输入个NAME,T-CODE.然后执行...最后用保存或者返回来结束录屏. 然后选择记录,创建 ...

  3. JButton计数

    1.引言 在Swing窗口中,我们时常会点击按钮进行计数,例如点击按钮A,第一次弹出窗口1,第二次弹出窗口2....以及按钮的快捷键设置. import java.awt.event.ActionEv ...

  4. chkconfig命令

    chkconfig --list                  #列出系统所有的服务启动情况chkconfig --add xxx           #增加xxx服务chkconfig --de ...

  5. php安装出现的部分错误

    在CentOS编译PHP5的时候有时会遇到以下的一些错误信息,基本上都可以通过yum安装相应的库来解决.以下是具体的一些解决办法: checking for BZip2 support… yes ch ...

  6. 使用ContentProvider管理联系人------搜索联系人

    此博客只实现了查询功能: import java.util.ArrayList; import android.os.Bundle;import android.provider.ContactsCo ...

  7. js克隆

    一.有什么用 不破坏原对象的属性 引入一些概念~ 原始数据类型(5种):undefined.null.number.string.boolean 引用数据类型(1种,也叫复合数据类型):object ...

  8. QQ2013登录报文简单分析(不可用于非法用途)

    [NO.1 2013-05-08 00:31:16 046 SEND 115字节]02 31 03 08 25 27 B5 88 6F 91 D2 03 00 00 00 0101 01 00 00 ...

  9. 二模 (5) day2

    第一题: 有 N 个人顺时针围在一圆桌上开会,他们对身高很敏感. 因此决定想使得任意相邻的两人的身高差距最大值最小. 如果答案不唯一,输出字典序最小的排列,指的是身高的排列.N<=50 解题过程 ...

  10. JAVA中StringBuffer类常用方法详解

    String是不变类,用String修改字符串会新建一个String对象,如果频繁的修改,将会产生很多的String对象,开销很大.因此java提供了一个StringBuffer类,这个类在修改字符串 ...