给定一个非空二叉树,返回其最大路径和。
本题中,路径被定义为一条从树中任意节点出发,达到任意节点的序列。该路径至少包含一个节点,且不一定经过根节点。
示例 1:
输入: [1,2,3]
1
/ \
2 3
输出: 6
示例 2:
输入: [-10,9,20,null,null,15,7]
-10
/
9 20
/
15 7
输出: 42
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/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):
trueval=float('-inf')
def maxPathSum(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.val=root.val
self.flag=0
flag=0
if root.left:
self.findleft(root.left,flag)
self.val+=self.flag
self.flag=0
if root.right:
self.findright(root.right,flag)
self.val+=self.flag
self.trueval=max(self.val,self.trueval)
return self.trueval
def findleft(self,root,flag):
self.maxPathSum(root)
flag+=root.val
if flag>self.flag:
self.flag=flag
if root.left:
self.findleft(root.left,flag)
if root.right:
self.findright(root.right,flag)
def findright(self,root,flag):
self.maxPathSum(root)
flag+=root.val
if flag>self.flag:
self.flag=flag
if root.left:
self.findleft(root.left,flag)
if root.right:
self.findright(root.right,flag)
想法很好,可惜超时了,总结原因,是因为在找子root的maxPathSum时,重复计算了很多数据
而且看了很多答案这样的思路确实有点难改,因为我没有回溯值,只有对变量的全局修改。
可见https://leetcode-cn.com/problems/binary-tree-maximum-path-sum/solution/er-cha-shu-de-zui-da-lu-jing-he-by-leetcode/把我的问题描述的很好。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def maxPathSum(self, root: TreeNode) -> int:
def max_gain(node):
nonlocal max_sum
if not node:
return 0
# max sum on the left and right sub-trees of node
left_gain = max(max_gain(node.left), 0)
right_gain = max(max_gain(node.right), 0)
# the price to start a new path where `node` is a highest node
price_newpath = node.val + left_gain + right_gain
# update max_sum if it's better to start a new path
max_sum = max(max_sum, price_newpath)
# for recursion :
# return the max gain if continue the same path
return node.val + max(left_gain, right_gain)
max_sum = float('-inf')
max_gain(root)
return max_sum
思路的区别在于,我在写该代码的时候是按照以根节点为必过的点来写算法,然后对每个节点执行相同的代码递归,这样就造成了巨大的重复计算。而答案中,对所有的点进行一次遍历,因为答案有回溯值而我没有,所以很难去改。思路差别还是比较大。