今天的三道题,涉及:
- 二叉树的层序遍历、深度遍历、层序遍历的迭代实现
- 完全二叉树、满二叉树(如何判断一颗树是否是满二叉树、如何计算满二叉树的节点数)
1. 04.二叉树的最大深度
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例: 给定二叉树 [3,9,20,null,null,15,7],
代码实现:
- 深度遍历
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if not root:return 0
return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
- 层序遍历
- 深度遍历的栈实现
2. 111.二叉树的最小深度
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明:叶子节点是指没有子节点的节点。
python代码实现
- 深度遍历
class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
# 深度优先搜索,根、左右/根、右左都行
if not root: return 0
if not root.right:
return self.minDepth(root.left) + 1
if not root.left:
return self.minDepth(root.right) + 1
return min(self.minDepth(root.left), self.minDepth(root.right)) + 1
- 层序遍历
from collections import deque
# 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 minDepth(self, root: Optional[TreeNode]) -> int:
# 层序遍历
if not root:return 0
queue = deque()
queue.append(root)
depth = 0
while queue:
for i in range(len(queue)):
root = queue.popleft()
depth += 1
if not root.left and not root.right:
return depth
if root.left:
queue.append(root.left)
if root.right:
queue.append(root.right)
return depth
- 深度遍历的栈实现
3. 222.完全二叉树的节点个数
给你一棵 完全二叉树 的根节点 root ,求出该树的节点个数。
完全二叉树 的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2h 个节点。
代码实现
两种实现方法:
- 非完全二叉树的实现
- 针对完全二叉树的实现
class Solution:
def countNodes(self, root: Optional[TreeNode]) -> int:
if not root: return 0
# 注释的代码是针对判断是否是满二叉树的代码,如果是满二叉树,则直接根据公式计算子树
# 的节点数
# left_depth, right_depth = 0, 0
# node = root
# while node.left:
# node = node.left
# left_depth += 1
# while node.right:
# node = node.right
# right_depth += 1
# if left_depth == right_depth:
# return 2 ** (left_depth + 1) - 1
return self.countNodes(root.left) + self.countNodes(root.right) + 1