# 111.Minimum Depth of Binary Tree(Tree-Easy)

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

Language：cpp

```/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int minDepth(TreeNode* root) {
if(!root) return 0;
int l = minDepth(root->left);
int r = minDepth(root->right);
return 1 + (l && r ? min(l, r) : max(l, r));
}
};```

Language：python

Python使用了两种方法，递归和迭代。通过运行对比发现，迭代的方法速度更快。

```# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
d = map(self.minDepth, (root.left, root.right))
return 1 + (min(d) or max(d))```

```# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
queue = [root]
height = 0
while queue:
# node = queue.pop(0)
height += 1
ls = []
for temp in queue:
if not temp.right and not temp.left:
return height
if temp.left:
ls.append(temp.left)
if temp.right:
ls.append(temp.right)
queue = ls
return height```

0 条评论

## 相关文章

2212

380

### LintCode 验证二叉查找树题目分析代码

2 / 1 4 / 3 5 上述这棵二叉树序列化为 {2,1,4,#,#,3,5}.

1122

2333

1155

1K7

5322

### LeetCode 102 & 103 ＆107 & 637. Binary Tree Level Order Traversal

Given a binary tree, return the level order traversal of its nodes' values. (ie,...

1010

4025

1534