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)])
相关文章推荐
- 利用python 完成leetcode111 二叉树的最小深度
- leetcode之二叉树类之二叉树深度系列-----104/111/110/108/109 二叉树最大/最小深度/AVL树的判断和由有序序列生成(牵扯分治相关,OJ105/106)
- [LeetCode 111] - 二叉树的最小深度 (Minimum Depth of Binary Tree)
- LeetCode-111.二叉树的最小深度(相关话题:深度优先)
- 【LeetCode-面试算法经典-Java实现】【111-Minimum Depth of Binary Tree(二叉树的最小深度)】
- LeetCode:111_Minimum Depth of Binary Tree | 二叉树的最小深度 | Easy
- leetcode 111-二叉树最小深度
- [LeetCode-111] Minimum Depth of Binary Tree (二叉树最小深度)
- 【LeetCode-面试算法经典-Java实现】【111-Minimum Depth of Binary Tree(二叉树的最小深度)】
- [LeetCode] 111. Minimum Depth of Binary Tree 二叉树的最小深度
- [Leetcode] The minimum depth of binary tree二叉树的最小深度
- Leetcode 111. Minimum Depth of Binary Tree 二叉树最小深度
- leetcode 二叉树最小深度
- LeetCode 二叉树的最小深度
- 【LeetCode】Minimum Depth of Binary Tree 二叉树的最小深度 java
- LeetCode 二叉树的最小深度
- [LeetCode]111. Minimum Depth of Binary Tree--二叉树的最小深度
- Minimum Depth of Binary Tree 求二叉树最小高度/深度@LeetCode
- Leetcode039--二叉树的最小深度
- LeetCode 111. Minimum Depth of Binary Tree (二叉树最小的深度)