【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 ...
随机推荐
- Permutations [LeetCode]
Given a collection of numbers, return all possible permutations. For example,[1,2,3] have the follow ...
- Struts2配置拦截器,struts2加载常量时的搜索顺序
1:struts2加载常量时的搜索顺序 1.Struts-default.xml 2.Struts-plugin.xml 3.Struts.xml 4.Struts-properties(自己创建的) ...
- BZOJ3308 九月的咖啡店
Orz PoPoQQQ 话说这题还有要注意的地方... 就是...不能加SLF优化,千万不能加 n = 40000,不加本机跑出来2sec,加了跑出来40sec...[给跪了 /*********** ...
- Linux CC攻击脚本
CC(ChallengeCollapsar)主要是用来攻击页面的.大家都有这样的经历,就是在访问论坛时,如果这个论坛比较大,访问的人比较多,打开页面的速度会比较慢,访问的人越多,论坛的页面越多,数据库 ...
- 使用MediaPlayer播放音频-----之二
MediaPlayer播放不同来源的音频文件: 一.播放应用的资源文件 1.调用MediaPlayer的create(Context context , int resid)方法加载指定资源文件. ...
- js获取URL地址中的GET参数
var $_GET = (function(){ var url = window.document.location.href.toString(); var u = url.split(" ...
- HDU 5313 bitset优化背包
题目大意: 添加尽可能少的边,最后使图形成二分图 一开始将图区分成一个个联通分量,根据二分图染色,计算出每个联通分量的黑色点和白色点的个数 希望添加的边最少,那么合并的时候,希望黑白块尽可能平均,这无 ...
- 大学生成绩管理系统(C语言)
功能:成绩管理系统包含了学生的全部信息,每个学生是一个记录,包括学号,姓名,性别,班级,各科成绩(语数外). 系统功能: 1.信息录入——录入学生信息: 2.信息输出——显示所有信息: 3.信息查询— ...
- 在线体验K2 BPM微信审批
“微信审批”在江湖中传言已久,但很多人依然“只闻其声,未见其人”,这传说中的手感到底有多好?今天,我们就一起来揭开它的真面目吧. 故事发生在上周六傍晚,我接到了加班电话. 晚上21:30终于加完班了, ...
- jquery判断点击事件是否为指定区域
<script type="text/javascript"> $(document).click(function(e){ e = window.event || e ...