Count Good Nodes in Binary Tree
LeetCode 1448 · मध्यम · समाधान, intuition और कदम-दर-कदम वॉकथ्रू
Pass the path maximum down.
मैंने Count Good Nodes in Binary Tree (LeetCode 1448) ऐसे हल किया — DFS Basics पैटर्न का एक मध्यम प्रॉब्लम। नीचे: intuition, कदम-दर-कदम approach, मेरा accepted Python कोड, animated test cases और line-by-line debugger।
नीचे का विवरण अंग्रेज़ी में है।
Intuition
A node is good if no node on the path from the root is larger. Carry the largest value seen on the current path down the recursion and compare.
Approach
- 1
dfs(node, max): None → 0.
- 2
Count 1 if node.val ≥ max.
- 3
Update max and add the counts from both children.
मैंने कैसे हल किया
DFS with path maxPythonO(n) time · O(h) space
class Solution:
def goodNodes(self, root):
def dfs(node, mx):
if node is None:
return 0
res = 1 if node.val >= mx else 0
mx = max(node.val, mx)
res += dfs(node.left, mx)
res += dfs(node.right, mx)
return res
return dfs(root, float("-inf"))Count Good Nodes in Binary Tree — अक्सर पूछे जाने वाले प्रश्न
Count Good Nodes in Binary Tree के पीछे intuition क्या है?
A node is good if no node on the path from the root is larger. Carry the largest value seen on the current path down the recursion and compare.
Count Good Nodes in Binary Tree (LeetCode 1448) कैसे हल करें?
1. dfs(node, max): None → 0. 2. Count 1 if node.val ≥ max. 3. Update max and add the counts from both children.
Count Good Nodes in Binary Tree की time और space complexity क्या है?
Time: O(n)। Space: O(h)। (Accepted approach: DFS with path max।)
Count Good Nodes in Binary Tree में आम गलतियाँ क्या हैं?
Use ≥ — equal values count as good.