Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit fac7140

Browse files
Create count_complete_tree_nodes.py
1 parent 8fe041d commit fac7140

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

‎day-25/count_complete_tree_nodes.py‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
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

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /