【LeetCode OJ】Binary Tree Maximum Path Sum
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的更多相关文章
- 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 ...
- 【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 ...
- 【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. ...
- 【LEETCODE OJ】Binary Tree Postorder Traversal
Problem Link: http://oj.leetcode.com/problems/binary-tree-postorder-traversal/ The post-order-traver ...
- 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 ...
- 【LeetCode OJ】Binary Tree Level Order Traversal
Problem Link: https://oj.leetcode.com/problems/binary-tree-level-order-traversal/ Traverse the tree ...
- 【LeetCode OJ】Binary Tree Zigzag Level Order Traversal
Problem Link: https://oj.leetcode.com/problems/binary-tree-zigzag-level-order-traversal/ Just BFS fr ...
- 【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 ...
- 【LEETCODE OJ】Binary Tree Preorder Traversal
Problem Link: http://oj.leetcode.com/problems/binary-tree-preorder-traversal/ Even iterative solutio ...
随机推荐
- js打印图形
1. js绘画金字塔 思想:先画n-i个空格,再画2*i-1个*号,再画n-i个空格(此处可以省略),一行画完之后换行:循环下一行(先判断每行的空格数和*号与行数间的关系) var n=window ...
- hdu--(1247)Hat’s Words(trie树)
Hat’s Words Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total ...
- DataTable常用操作
添加列和行的三种方法(转载) 原文地址:http://www.cnblogs.com/jRoger/articles/1887581.html DataTable tblDatas =new Data ...
- WebForm MapPageRoute 路由配置(转载)
使用场景是:MVC 混合使用 WebForm,然后对 WebForm 进行路由配置 http://www.cnblogs.com/xishuai/archive/2015/02/26/web-form ...
- wordpress+php+mysql 配置
下载并解压wordpress之后,在mysql新建一个数据库,命名,例如testDB1,然后在IIS中新建虚拟目录,指向wordress所在的目录,删除wordpress目录下的wp-config.p ...
- offsetLeft,Left,clientLeft的区别
offsetLeft,Left,clientLeft的区别 假设 obj 为某个 HTML 控件. obj.offsetTop 指 obj 相对于版面或由 offsetParent 属性指定的父坐标的 ...
- tomcat 集群配置,Session复制共享
本配置在tomcat7上验证通过.通过此方法配置的集群,session信息将会被自动复制到各个节点. 1.配置Server.xml 在Server.xml中,找到被注释<Cluster/> ...
- redhat enterprixe 5.0 web 服务配置与管理
一.Web服务及工作原理 Web服务的实现采用客户/服务器模型.客户机运行Web客户程序(浏览器),作用是解释和显示Web页面,相应用户的输入请求,并且通过http协议将用户请求传递给Web服务器.W ...
- 闭包 (循环事件获取不到i) 和 各种解决循环获取不到i的解决方法
for(var i in fav){ (function(){ var p=i; var obj=$S.getId(fav[i]); ...
- 二模 (7) day1
第一题: 题目大意: 给出数轴上N棵树的坐标和高度,如果两棵树之间的距离小于其中一颗树的高度,那么就有树会被挡住.因此要把一些树砍矮一点.求砍树的总高度最小值. N<=100000; 解题过程: ...