-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCount Complete Tree Nodes.py
More file actions
41 lines (33 loc) · 921 Bytes
/
Count Complete Tree Nodes.py
File metadata and controls
41 lines (33 loc) · 921 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
'''
Given a complete binary tree, count the number of nodes.
Note:
Definition of a complete binary tree from Wikipedia:
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.
Example:
Input:
1
/ \
2 3
/ \ /
4 5 6
Output: 6
'''
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def countNodes(self, root):
"""
:type root: TreeNode
:rtype: int
"""
return self.count(root)
def count(self, node):
if not node:
return 0
left = self.count(node.left)
right = self.count(node.right)
return left + right + 1