Leetcode原题链接:
二叉树的最小深度
一、思路
- 见二叉树首先考虑遍历,本题的确适合从遍历入手。
- 求深度自然采用了后序遍历(左右中),左右孩子算出深度再传给父亲节点。
- 遍历方法选择:递归——合适;迭代——不合适,普通的迭代法不包含层的概念;层序——合适。
- 求最小深度的一个误区:根据题目,根节点到叶子结点的距离为深度,因此只有左右孩子均为空的时候,才能当做当前深度。
二、代码
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 minDepth(self, root):
return self.getDepth(root)
def getDepth(self, node):
if node is None:
return 0
leftDepth = self.getDepth(node.left) # 左
rightDepth = self.getDepth(node.right) # 右
# 当一个左子树为空,右不为空,这时并不是最低点
if node.left is None and node.right is not None:
return 1 + rightDepth
# 当一个右子树为空,左不为空,这时并不是最低点
if node.left is not None and node.right is None:
return 1 + leftDepth
result = 1 + min(leftDepth, rightDepth)
return result
2、层序遍历
# 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):
if not root:
return 0
queue = [root]
depth = 0
while queue:
depth += 1
for i in range(len(queue)):
node = queue.pop(0)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
if not node.left and not node.right:
return depth
三、总结
- 递归三部曲这次倒是记下来了,用的也合适,但是没考虑好递归逻辑,因此没写出来,本题最小深度需要深入思考在逻辑上到底该返回什么值
部分内容参考代码随想录