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.