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

文章目录

  • 一、题目描述
      • 示例 1![在这里插入图片描述](https://img-blog.csdnimg.cn/8c74d1b796b74286999e09d4c6b7682f.png#pic_center)
      • 示例 2
      • 示例 3
  • 二、代码
  • 三、解题思路


一、题目描述

给你一棵 完全二叉树 的根节点 root ,求出该树的节点个数。

完全二叉树 的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2^h 个节点。

示例 1222. 完全二叉树的节点个数 Python_第1张图片

输入:root = [1,2,3,4,5,6]
输出:6

示例 2

输入:root = []
输出:0

示例 3

输入:root = [1]
输出:1

提示:
树中节点的数目范围是[0, 5 * 10^4]
0 <= Node.val <= 5 * 10^4
题目数据保证输入的树是 完全二叉树

二、代码

代码如下:

# 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:
        def findCount(r):
            if r is None:
                return
            if r.left is not None:
                count[0] += 1
                findCount(r.left)
            if r.right is not None:
                count[0] += 1
                findCount(r.right)
        if root is not None:
            count = [1]
        else:
            count = [0]
        findCount(root)
        print(count[0])
        return count[0]



三、解题思路

本题考验对于二叉树的遍历操作,在遍历节点时需要计数,采用最普通的遍历操作即可满足题意。

你可能感兴趣的:(LeetCode中等难度题集,算法,数据结构,python,leetcode)