104.二叉树的最大深度
首先明确二叉树的高度和深度概念:
节点的高度:该节点到最远叶子节点的最长路径上的边的数量。叶子结点的高度为0。
节点的深度:从根节点到该节点的路径上的边的数量。根节点的深度为 0。
如果求节点的高度,应该从下至上,采用后序遍历。
如果求节点的深度,应该从上至下,采用前序遍历。
本题求解最大深度,但根节点的高度等于二叉树的最大深度,因此两者都可行。并且,本题也可以采用层序遍历。
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
# 层序遍历
if not root:
return 0
queue = deque([root])
depth = 0
while queue:
# 每层遍历值+1
depth += 1
for _ in range(len(queue)):
node = queue.popleft()
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return depth
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
# 前序遍历:递归
if not root:
return 0
leftdepth = self.maxDepth(root.left)
rightdepth = self.maxDepth(root.right)
depth = 1 + max(leftdepth, rightdepth)
return depth
111.二叉树的最小深度
最小深度:根节点到最近叶子节点的路径边数,没有子节点的节点叫叶子结点。
class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
# 层序遍历
if not root:
return 0
queue = deque([root])
depth = 0
while queue:
depth += 1
for _ in range(len(queue)):
node = queue.popleft()
if not node.left and not node.right:
return depth
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return depth
class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
# 如果一个节点只有一个子节点,我们只计算有子节点那一边的最小深度。
# 如果一个节点有两个子节点,我们计算左右子树的最小深度,取其中的较小值。
if not root.left:
return self.minDepth(root.right) + 1
if not root.right:
return self.minDepth(root.left) + 1
return min(self.minDepth(root.left), self.minDepth(root.right)) + 1
222.完全二叉树的节点个数
我们可以当作普通二叉树进行遍历,这里提供前序遍历的递归写法和层序遍历。
class Solution:
def countNodes(self, root: Optional[TreeNode]) -> int:
# 前序遍历:递归
if not root:
return 0
leftNum = self.countNodes(root.left) # 左
rightNum = self.countNodes(root.right) # 右
count = leftNum + rightNum + 1 # 中
return count
# 时间复杂度:
# O(n)
class Solution:
def countNodes(self, root: Optional[TreeNode]) -> int:
# 层序遍历
if not root:
return 0
queue = deque([root])
count = 0
while queue:
level_size = len(queue)
for _ in range(level_size):
node = queue.popleft()
count += 1
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return count
但本题可以利用完全二叉树的定义求解,无需遍历所有节点。
在完全二叉树中,除了最底层外,其他每层节点数都达到最大值,且最底层的节点集中在左侧。这意味着如果一棵完全二叉树的最左侧路径的深度等于最右侧路径的深度,那么这棵树是满二叉树,其节点数可以直接通过 2^n − 1 计算。
即使它不是满二叉树,其左子树或右子树之一必然是一棵满二叉树,这使得我们可以利用这个性质递归地计算节点数,
class Solution:
def countNodes(self, root: Optional[TreeNode]) -> int:
# 递归
if not root: return 0
count = 1
left = root.left
right = root.right
# 同时向最左和最右侧路径遍历
while left and right:
count += 1
left = left.left
right = right.right
# 如果有一个为空,则说明左右路经不同
# 如果路径相同,则说明是满二叉树
if not left and not right:
return 2**count - 1
return 1 + self.countNodes(root.left) + self.countNodes(root.right)
# 时间复杂度:
# O(logn * lögn)