|
| 1 | +# Problem: Count Complete Tree Nodes |
| 2 | +# Link: https://leetcode.com/problems/count-complete-tree-nodes/description/ |
| 3 | +# Tags: Binary Tree, DFS, Divide and Conquer, Binary Search |
| 4 | +# Approach: |
| 5 | +# Use the properties of complete binary trees. At each node, compute the height of the left |
| 6 | +# and right subtrees. If the heights are equal, the left subtree is perfect (completely filled), |
| 7 | +# so its node count is 2^h - 1; continue counting recursively on the right subtree. If the |
| 8 | +# heights differ, the right subtree is perfect with 2^h - 1 nodes, and recursion continues |
| 9 | +# on the left subtree. This reduces traversal significantly compared to naive DFS. |
| 10 | +# Time Complexity: O((log n)^2) – computing height is O(log n) and we do it for O(log n) levels |
| 11 | +# Space Complexity: O(log n) – recursion depth equal to the tree height |
| 12 | + |
| 13 | + |
| 14 | +class Solution: |
| 15 | + def countNodes(self, root): |
| 16 | + if not root: |
| 17 | + return 0 |
| 18 | + |
| 19 | + def getHeight(node): |
| 20 | + h = 0 |
| 21 | + while node: |
| 22 | + h += 1 |
| 23 | + node = node.left |
| 24 | + return h |
| 25 | + |
| 26 | + left_h = getHeight(root.left) |
| 27 | + right_h = getHeight(root.right) |
| 28 | + |
| 29 | + if left_h == right_h: |
| 30 | + # left subtree is perfect |
| 31 | + return (1 << left_h) + self.countNodes(root.right) |
| 32 | + else: |
| 33 | + # right subtree is perfect |
| 34 | + return (1 << right_h) + self.countNodes(root.left) |
0 commit comments