LeetCode 222. Count Complete Tree Nodes

题目

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 2^h nodes inclusive at the last level h.

Example:

1
2
3
4
5
6
7
8
Input: 
1
/ \
2 3
/ \ /
4 5 6

Output: 6

思路

Recursive.

代码

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
42
43
44
45
46
47
# # Definition for a binary tree node.
# # class TreeNode(object):
# # def __init__(self, val=0, left=None, right=None):
# # self.val = val
# # self.left = left
# # self.right = right
# class Solution(object):
# def countNodes(self, root):
# """
# :type root: TreeNode
# :rtype: int
# """
# if not root:
# return 0
# nodes = 0
# left = self.getHeight(root.left)
# right = self.getHeight(root.right)
# if left == right:
# nodes = 2 ** left + self.countNodes(root.right)
# else:
# nodes = 2 ** right +self.countNodes(root.left)
# return nodes


# def getHeight(self, root):
# height = 0
# while root:
# height += 1
# root = root.left
# return height


# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def countNodes(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
return 1 + self.countNodes(root.left) + self.countNodes(root.right)