222. 完全二叉树的节点个数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def countNodes(self, root: Optional[TreeNode]) -> int:
num = 0
if root != None:
num = 1
num += self.countNodes(root.left)
num += self.countNodes(root.right)
return num