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.