解法:
同我的心路,任何时候二叉树自顶向下的方法都会涉及很多重复的计算,所以需要经常需要递归来提高效率。
自底向上的递归法,在每点可能的最大路径有三种可能:
i. max(left subtree) + node
ii. max(right subtree) + node
iii. max(left subtree) + max(right subtree) + node
iv. node
递归函数中要返回包含该Node和某一子树的最大路径和,此处,若某子树返回值为负,则置该值为0,而只包含该节点,如此一来可以极大简化代码。(此处是关键,我的代码中,为了排除子树为空的情况,增加了列表变量,让代码复杂了很多)
Python源码:
Runtime: 80 ms, faster than 76.98% of Python online submissions for Binary Tree Maximum Path Sum.
Memory Usage: 24.2 MB, less than 75.00% of Python online submissions for Binary Tree Maximum Path Sum.
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):\
def maxPathSum(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.max_sum = -2417483648
self.get_max(root)
return self.max_sum
def get_max(self, node):
if node == None:
return 0
left = self.get_max(node.left)
right = self.get_max(node.right)
self.max_sum = max(self.max_sum, left+right+node.val)
ret = max(left, right) + node.val
if ret > 0:
return ret
else:
return 0
我的心路:
这是一道hard题,题目求二叉树的最大和路径。我的思路依然是递归求解,但保存全局变量max,用来计算包含左右子树路径这一情况,因为一条路径最多只能包含一次左右子树,所以该方法是可行的。过程中还需要考虑的一点是最小值的问题,我采用了设标志的方法,杜绝了环境不同最小值不同这一问题(后来其实想想直接赋值为root的val就可以了。。)。最终runtime成绩不理想。
Runtime: 108 ms, faster than 8.23% of Python online submissions for Binary Tree Maximum Path Sum.
Memory Usage: 24.5 MB, less than 70.00% of Python online submissions for Binary Tree Maximum Path Sum.
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):\
def maxPathSum(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.found_one = False
self.max_path_sum = 0
self.get_maxPathSum(root)
return self.max_path_sum
def get_maxPathSum(self, node):
cands_max = []
cands_ret = []
cands_max.append(node.val)
cands_ret.append(node.val)
if node.left:
left_max = self.get_maxPathSum(node.left)
cands_ret.append(left_max+node.val)
cands_max.append(left_max)
cands_max.append(left_max+node.val)
if node.right:
right_max = self.get_maxPathSum(node.right)
cands_ret.append(right_max+node.val)
cands_max.append(right_max)
cands_max.append(right_max+node.val)
if node.left:
cands_max.append(right_max+node.val+left_max)
if self.found_one:
self.max_path_sum = max(self.max_path_sum, max(cands_max))
else:
self.max_path_sum = node.val
self.found_one = True
return max(cands_ret)