222 完全二叉树的节点个数
给你一棵 完全二叉树 的根节点 root ,求出该树的节点个数。
完全二叉树 的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2h 个节点。
输入:root = [1,2,3,4,5,6]
输出:6
输入:root = [1]
输出:1
# 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:
# 非递归
# results = []
# if not root:return 0
# from collections import deque
# que = deque([root])
# while que:
# result = []
# n = len(que)
# for _ in range(n):
# cur = que.popleft()
# result.append(cur.val)
# if cur.left:
# que.append(cur.left)
# if cur.right:
# que.append(cur.right)
# results.extend(result)
# return len(results)
# 递归
res = []
if not root:return 0
def helper(root, depth):
if len(res) == depth:res.append([])
res[depth].append(root.val)
if root.left:
helper(root.left, depth+1)
if root.right:
helper(root.right, depth+1)
helper(root, 0)
count = 0
for i in res:count += len(i)
return count