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.