Code Review Asked on December 2, 2021
I’m posting my code for a LeetCode problem. If you’d like to review, please do so. Thank you for your time!
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.
Input: [1,2,3]
1
/
2 3
Output: 6
Input: [-10,9,20,null,null,15,7]
-10
/
9 20
/
15 7
Output: 42
[1,2,3]
[-10,9,20,null,null,15,7]
[-10,9,20,null,null,15,7,9,20,null,null,15,7]
[-10,9,20,null,null,15,7,9,20,null,null,15,720,null,null,15,7,9,20,null,null,15,7]
[-10,9,20,null,null,15,7,9,20,null,null,15,720,null,null,15,7,9,20,null,null,15,7999999,20,null,null,15,7,9,20,null,null,15,720,null,null,15,7,9,20,null,null,15,7]
6
42
66
791
8001552
# 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: TreeNode) -> int:
def depth_first_search(node: TreeNode) -> int:
if not node:
return 0
left_sum = depth_first_search(node.left)
right_sum = depth_first_search(node.right)
if not left_sum or left_sum < 0:
left_sum = 0
if not right_sum or right_sum < 0:
right_sum = 0
self.sum = max(self.sum, left_sum + right_sum + node.val)
return max(left_sum, right_sum) + node.val
self.sum = float('-inf')
depth_first_search(root)
return self.sum
depth_first_search()
The function depth_first_search()
always returns an integer value, never None
. So the check for a partial sum being None
or < 0
can be rewritten using max()
:
left_sum = max(0, depth_first_search(node.left))
right_sum = max(0, depth_first_search(node.right))
Answered by G. Sliepen on December 2, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP