leedcode-完全二叉树的节点个数
自己写的,使用广度优先BFS,迭代:
class Solution: def countNodes(self, root: Optional[TreeNode]) -> int: # 如果根节点为空,则树中节点数为 0 if not root: return 0 # 初始化队列,并将根节点放入队列中 queue = [root] # 计数器,初始值为 1,因为根节点已经算作一个节点了 count = 1 # 遍历队列,直到队列为空 while queue: # 弹出队列中的第一个节点 cur = queue.pop(0) # 如果当前节点有左子节点,将左子节点加入队列,并将计数器加一 if cur.left: queue.append(cur.left) count += 1 # 如果当前节点有右子节点,将右子节点加入队列,并将计数器加一 if cur.right: queue.append(cur.right) count += 1 # 返回计数器的值,即树中节点的总数 return count
利用完全二叉树的特性实现:
# 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 height(self, root:TreeNode): height = 0 while root: root = root.left height += 1 return height def countNodes(self, root: TreeNode) -> int: # 空树,节点数为 0 if root == None: return 0 # 求左子树和右子树的深度 leftHeight = self.height(root.left) rightHeight = self.height(root.right) # 如果左子树的深度 = 右子树的深度,左子树为满二叉树 # 节点数 = 左子树的深度 + 右子树的深度 + 根节点 if leftHeight == rightHeight: return (2 ** leftHeight - 1) + self.countNodes(root.right) + 1 # 如果左子树的深度 > 右子树的深度,右子树为满二叉树 # 节点数 = 左子树的深度 + 右子树的深度 + 根节点 else: return (2 ** rightHeight - 1) + self.countNodes(root.left) + 1
纯递归:
class Solution: def countNodes(self, root: Optional[TreeNode]) -> int: # 如果根节点为空,则返回 0 if not root: return 0 # 递归计算左子树的节点数 leftcount = self.countNodes(root.left) # 递归计算右子树的节点数 rightcount = self.countNodes(root.right) # 返回左右子树节点数之和加上根节点,即整棵树的节点数 return leftcount + rightcount + 1

浙公网安备 33010602011771号