Skip to content

Commit 1af04af

Browse files
authored
Create Count Complete Tree Nodes.py
1 parent 66fe3d6 commit 1af04af

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

Count Complete Tree Nodes.py

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
'''
2+
Given a complete binary tree, count the number of nodes.
3+
4+
Note:
5+
6+
Definition of a complete binary tree from Wikipedia:
7+
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.
8+
9+
Example:
10+
11+
Input:
12+
1
13+
/ \
14+
2 3
15+
/ \ /
16+
4 5 6
17+
18+
Output: 6
19+
'''
20+
21+
# Definition for a binary tree node.
22+
# class TreeNode(object):
23+
# def __init__(self, x):
24+
# self.val = x
25+
# self.left = None
26+
# self.right = None
27+
28+
class Solution(object):
29+
def countNodes(self, root):
30+
"""
31+
:type root: TreeNode
32+
:rtype: int
33+
"""
34+
return self.count(root)
35+
36+
def count(self, node):
37+
if not node:
38+
return 0
39+
left = self.count(node.left)
40+
right = self.count(node.right)
41+
return left + right + 1

0 commit comments

Comments
 (0)