Leetcode 124. Binary Tree Maximum Path Sum
Given a non-empty binary tree, find the maximum path sum.
For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.
Example 1:
Input: [1,2,3] 1 / \ 2 3 Output: 6
Example 2:
Input: [-10,9,20,null,null,15,7] -10 / \ 9 20 / \ 15 7 Output: 42
一开始写的方法是,将整个链表树变成图,然后找图的最大有效路径,代码如下:
# 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:
if(root == None):
return 0
elif(root.left == None and root.right == None):
return root.val
num = self.countNum(root)
#create a tree graph
num = num + 1
TreeGraph = [0]*num*num
print(num)
curPoint1 = 0
curPoint2 = 1
stack = []
stack.append(root)
TreeGraph[curPoint1*num+curPoint2]=root.val
TreeGraph[curPoint2*num+curPoint1]=root.val
while len(stack)!= 0:
cur = stack.pop()
curPoint1 = curPoint1 + 1
if cur.left!= None:
stack.append(cur.left)
curPoint2 = curPoint2 +1
print(curPoint1,curPoint2,cur.left.val)
TreeGraph[curPoint1*num+curPoint2] = cur.left.val
TreeGraph[curPoint2*num+curPoint1] = cur.left.val
if cur.right != None:
stack.append(cur.right)
curPoint2 = curPoint2 + 1
print(curPoint1,curPoint2,cur.right.val)
TreeGraph[curPoint1*num+curPoint2] = cur.right.val
TreeGraph[curPoint2*num+curPoint1] = cur.right.val
print(TreeGraph)
#build finish
for i in range(num):
for j in range(num):
if i!=j:
for k in range(num):
if i!=k and j!=k:
if(TreeGraph[i*num+j] < TreeGraph[i*num+k]+TreeGraph[k*num+j] and TreeGraph[i*num+k]!=0 and TreeGraph[k*num+i]!=0):
TreeGraph[i*num+j] = TreeGraph[i*num+k]+TreeGraph[k*num+j]
print(TreeGraph,i,k,j)
return max(TreeGraph)
def countNum(self, root:TreeNode)->int:
if(root == None):
return 0
return (1 + self.countNum(root.left) + self.countNum(root.right))
可以说是很麻烦的方法了,不是很Geek,同时也超过了时间限制。
查看了别人的方法,递归真是个好东西。
class Solution:
def maxPathSum(self, root):
"""
:type root: TreeNode
:rtype: int
"""
res = float('-inf')
def maxPath(node):
nonlocal res
if not node:
return 0
left = max(0, maxPath(node.left))
right = max(0, maxPath(node.right))
res = max(res, left + right + node.val)
return max(left, right) + node.val