Skip to content

Commit 79cd2d5

Browse files
authored
Create 222_Count_Complete_Tree_Nodes.md
1 parent 825aecb commit 79cd2d5

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

222_Count_Complete_Tree_Nodes.md

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
## 222. Count Complete Tree Nodes
2+
3+
```
4+
Given a complete binary tree, count the number of nodes.
5+
6+
Note:
7+
8+
Definition of a complete binary tree from Wikipedia:
9+
In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.
10+
11+
Example:
12+
13+
Input:
14+
1
15+
/ \
16+
2 3
17+
/ \ /
18+
4 5 6
19+
20+
Output: 6
21+
22+
```
23+
24+
25+
```python
26+
class Solution:
27+
def countNodes(self, root: TreeNode) -> int:
28+
if not root: return 0
29+
# check depth
30+
ld = self.check_depth(root, True)
31+
rd = self.check_depth(root, False)
32+
# print(ld)
33+
# print(rd)
34+
if ld == rd:
35+
return int(math.pow(2, ld)-1)
36+
return int(1 + self.countNodes(root.left) + self.countNodes(root.right))
37+
38+
def check_depth(self, root, lr):
39+
if not root: return 0
40+
if lr:
41+
d = self.check_depth(root.left, lr)
42+
else:
43+
d = self.check_depth(root.right, lr)
44+
45+
return d + 1
46+
```
47+
48+
```
49+
Runtime: 64 ms, faster than 98.98% of Python3 online submissions for Count Complete Tree Nodes.
50+
Memory Usage: 21.3 MB, less than 100.00% of Python3 online submissions for Count Complete Tree Nodes.
51+
52+
```

0 commit comments

Comments
 (0)