最小路径
二叉树中的最小路径指的是,二叉树中根节点到达叶子节点的路径中,距离最短的一个。
//recursively
public int minDepth1(TreeNode root) {
if (root == null) {
return 0;
} else if (root.left != null && root.right != null) {
return 1+Math.min(minDepth(root.left), minDepth(root.right));
} else {
return 1+Math.max(minDepth(root.left), minDepth(root.right));
}
}
// iteratively, BFS
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
int depth = 1;
while (!queue.isEmpty()) {
int l = queue.size();
for (int i = 0; i < l; i++) {
TreeNode n = queue.poll();
if (n.left == null && n.right == null) {
return depth;
}
if (n.left != null) {
queue.add(n.left);
}
if (n.right != null) {
queue.add(n.right);
}
}
depth++;
}
return depth;
}