您的位置:首页 > 编程语言 > Python开发

Leetcode 111 python 二叉树的最小深度

2019-03-08 18:44 716 查看

题意:

给定一个二叉树,找出其最小深度(从根节点到最近叶子节点的最短路径上的节点数量)。

说明: 叶子节点是指没有子节点的节点

示例:

给定二叉树 [3,9,20,null,null,15,7],

3
/ \
9  20
/  \
15   7

返回它的最小深度 2.

方法一:栈

利用层次遍历,按层次打印结点的,将其稍做修改。用变量i记录当前层数,当遇到叶子结点时则返回当前层数。

if root is None:
return 0
p = [root]
current_level_num = 1
next_level_num = 0
i = 1
while p:
current = p.pop(0)
current_level_num-=1
#遇到叶子节点时返回层数
if current.left is None and current.right is None:
return i

if current.left:
next_level_num+=1
p.append(current.left)
if current.right:
next_level_num+=1
p.append(current.right)
#当前层的节点遍历结束后层数加1,更新当前层的层数
if current_level_num == 0:
i += 1
current_level_num = next_level_num
next_level_num = 0

方法二:递归

递归有以下几种情况:
1.根节点为空,深度为0
2.只有一个根节点。深度为1
3.左右子树皆不空,则返回1+左右子树中最小的深度。
4.左子树为空,则返回1+右子树深度。这里可能有点难以理解,可以想象成此时只有根节点a,以及其右子树b,此时最小深度为2。
5.右子树为空,则返回1+左子树深度。同上分析

if root is None:
return 0
if root.left is None and root.right is None:
return 1
elif root.left is None:
return 1 + self.minDepth(root.right)
elif root.right is None:
return 1 + self.minDepth(root.left)
else:
return 1 + min([self.minDepth(root.left), self.minDepth(root.right)])
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: