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.