path sum
은 그 path의 node 값 들의 합# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def maxPathSum(self, root: Optional[TreeNode]) -> int:
global path
path = set()
recursion(root)
return max(path)
def recursion(root):
global path
leftTree, rightTree = 0, 0
if root.left:
leftTree = recursion(root.left)
if root.right:
rightTree = recursion(root.right)
pathSum = [root.val]
pathSum.append(leftTree + root.val) # left+root
pathSum.append(rightTree + root.val) # right+root
pathSum.append(leftTree + rightTree + root.val) # left + right + root
path.add(max(pathSum))
return max(pathSum[:3])
돌릴때마다 속도가 달라져..... 76.87% 속도 나올것같다
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def maxPathSum(self, root: Optional[TreeNode]) -> int:
global maxi
maxi = -1001
recursion(root)
return maxi
def recursion(root):
global maxi
leftTree, rightTree = 0, 0
if root.left:
leftTree = recursion(root.left)
if root.right:
rightTree = recursion(root.right)
pathSum = [root.val]
pathSum.append(leftTree + root.val) # left+root
pathSum.append(rightTree + root.val) # right+root
pathSum.append(leftTree + rightTree + root.val) # left + right + root
maxi = max(maxi, max(pathSum))
return max(pathSum[:3])
이건 set에 넣는대신, 그때 그때 max 연산을 돌려주었다
크게 차이나진 않는다