Binary Tree Maximum Path Sum — LeetCode 124 Python Solution
- Problem
- #124
- Pattern
- Tree Traversal
- Reading time
- 4 min
- Source
- leetcode.com
The problem
A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once.
Example
- Input
- root = [1,2,3]
- Output
- 6
- Explanation
- The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6.
Python solution
# 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:
def dfs(root: Optional[TreeNode]) -> int:
if root is None:
return 0
left = max(0, dfs(root.left))
right = max(0, dfs(root.right))
nonlocal ans
ans = max(ans, root.val + left + right)
return root.val + max(left, right)
ans = -inf
dfs(root)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Tree Traversal
Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 124. Binary Tree Maximum Path Sum is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.
The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
On study lists
This problem is on Blind 75, NeetCode 150 and Top Interview 150.
Frequently asked questions
- How hard is LeetCode 124. Binary Tree Maximum Path Sum?
- LeetCode 124. Binary Tree Maximum Path Sum is rated Hard on LeetCode.
- What is the time complexity of LeetCode 124. Binary Tree Maximum Path Sum?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 124. Binary Tree Maximum Path Sum?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 124. Binary Tree Maximum Path Sum cover?
- LeetCode 124. Binary Tree Maximum Path Sum is tagged Tree, Depth-First Search, Dynamic Programming and Binary Tree on LeetCode.