Count Complete Tree Nodes
LeetCode 222 · मध्यम · समाधान, intuition और कदम-दर-कदम वॉकथ्रू
count = 1 + count(left) + count(right).
मैंने Count Complete Tree Nodes (LeetCode 222) ऐसे हल किया — Other पैटर्न का एक मध्यम प्रॉब्लम। नीचे: intuition, कदम-दर-कदम approach, मेरा accepted Python कोड, animated test cases और line-by-line debugger।
नीचे का विवरण अंग्रेज़ी में है।
Intuition
Counting every node recursively is the simplest correct answer: one for the root plus the counts of both subtrees.
Approach
- 1
Empty → 0; leaf → 1.
- 2
Otherwise 1 + both subtree counts.
मैंने कैसे हल किया
Recursive countPythonO(n) time
class Solution:
def countNodes(self, root):
if root is None:
return 0
if root.left is None and root.right is None:
return 1
return 1 + self.countNodes(root.left) + self.countNodes(root.right)Count Complete Tree Nodes — अक्सर पूछे जाने वाले प्रश्न
Count Complete Tree Nodes के पीछे intuition क्या है?
Counting every node recursively is the simplest correct answer: one for the root plus the counts of both subtrees.
Count Complete Tree Nodes (LeetCode 222) कैसे हल करें?
1. Empty → 0; leaf → 1. 2. Otherwise 1 + both subtree counts.
Count Complete Tree Nodes की time और space complexity क्या है?
Time: O(n)। Space: O(log n) for a complete tree। (Accepted approach: Recursive count।)
Count Complete Tree Nodes में आम गलतियाँ क्या हैं?
Comparing left and right heights gives O(log² n) by using completeness.