Binary Tree Maximum Path Sum
LeetCode 124 · कठीण · उपाय, intuition आणि टप्प्याटप्प्याने वॉकथ्रू
Update the answer with both sides; return only one side to the parent.
मी Binary Tree Maximum Path Sum (LeetCode 124) असा सोडवला — Tree DP पॅटर्नमधील एक कठीण प्रॉब्लेम. खाली: intuition, टप्प्याटप्प्याने approach, माझा accepted Python कोड, animated test cases आणि line-by-line debugger.
खालील विवरण इंग्रजीत आहे.
Intuition
Every path has a highest node where it bends. At each node, the best path bending there is node + best downward gain from the left + best downward gain from the right. But a path passed up to the parent can only continue down one side, so return node + the better single side. Negative gains are dropped as 0.
Approach
- 1
dfs(node) returns the best downward path sum starting at node.
- 2
Left and right gains are clipped at 0 — a negative branch is better left out.
- 3
Update the global best with node.val + left + right (the bend at this node).
- 4
Return node.val + max(left, right) to the parent.
मी कसा सोडवला
Post-order DFS (tree DP)PythonO(n) time · O(h) space
# 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:
max_sum = float("-inf")
def dfs(node):
nonlocal max_sum
if node==None:
return 0
left = max(0,dfs(node.left))
right = max(0,dfs(node.right))
max_sum=max(max_sum,node.val+left+right)
return node.val+max(left,right)
dfs(root)
return max_sumBinary Tree Maximum Path Sum — वारंवार विचारले जाणारे प्रश्न
Binary Tree Maximum Path Sum मागील intuition काय आहे?
Every path has a highest node where it bends. At each node, the best path bending there is node + best downward gain from the left + best downward gain from the right. But a path passed up to the parent can only continue down one side, so return node + the better single side. Negative gains are dropped as 0.
Binary Tree Maximum Path Sum (LeetCode 124) कसा सोडवावा?
1. dfs(node) returns the best downward path sum starting at node. 2. Left and right gains are clipped at 0 — a negative branch is better left out. 3. Update the global best with node.val + left + right (the bend at this node). 4. Return node.val + max(left, right) to the parent.
Binary Tree Maximum Path Sum ची time आणि space complexity किती आहे?
Time: O(n). Space: O(h) recursion. (Accepted approach: Post-order DFS (tree DP).)
Binary Tree Maximum Path Sum मध्ये सामान्य चुका कोणत्या?
Start the global best at −∞ — an all-negative tree must return its largest value. Returning both sides to the parent would create a forked, invalid path.