Tensorum
YouTubeనేర్చుకోవడం ప్రారంభించండి
LeetCode 222 · Other

Count Complete Tree Nodes

LeetCode 222 · మధ్యస్థం · పరిష్కారం, intuition & దశలవారీ వాక్‌త్రూ

count = 1 + count(left) + count(right).

మధ్యస్థంBinary SearchBit ManipulationTreeBinary Tree
LeetCode లో తెరవండి ↗

నేను 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. 1

    Empty → 0; leaf → 1.

  2. 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.