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.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7]
,
3
/ \
9 20
/ \
15 7
return its minimum depth = 2.
有个trick是不能直接用height = 1+min(self.minDepth(root.left),self.minDepth(root.right))
。因为这样的话不能保证深度是从叶结点开始算的。比如下面的情况就会返回1而不是2.
3
/
1
所以需要讨论左右是不是None的情况。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
if root.left and root.right:
height = 1+min(self.minDepth(root.left),self.minDepth(root.right))
elif root.left:
height = 1+self.minDepth(root.left)
elif root.right:
height = 1+self.minDepth(root.right)
else:
height = 1
return height
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int res = Integer.MAX_VALUE;
private void helper(TreeNode root, int cur)
{
if(root == null)
return;
else if(root.left == null && root.right == null)
res = (cur+1)<res? cur+1:res;
else
{
helper(root.right,cur+1);
helper(root.left,cur+1);
}
}
public int minDepth(TreeNode root) {
int cur = 0;
if(root==null)
return 0;
helper(root,cur);
return res;
}
}