Minimum Depth of Binary Tree (E)
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.
题意
找到给定树从根到叶结点(两子树都为空的结点)的最短距离。
思路
递归或迭代。
代码实现 - 递归
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
int lDepth = minDepth(root.left);
int rDepth = minDepth(root.right);
if (lDepth == 0) {
return rDepth + 1;
} else if (rDepth == 0) {
return lDepth + 1;
} else {
return Math.min(lDepth, rDepth) + 1;
}
}
}
代码实现 - 迭代
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
Queue<TreeNode> q = new ArrayDeque<>();
int depth = 0;
q.offer(root);
while (!q.isEmpty()) {
depth++;
int size = q.size();
for (int i = 0; i < size; i++) {
TreeNode cur = q.poll();
// 第一次找到叶结点,说明已经为最短距离
if (cur.left == null && cur.right == null) {
return depth;
}
if (cur.left != null) {
q.offer(cur.left);
}
if (cur.right != null) {
q.offer(cur.right);
}
}
}
return depth;
}
}
本文探讨了在给定的二叉树中寻找从根节点到最近叶节点的最短路径的问题,通过递归和迭代两种方法实现了MinimumDepthofBinaryTree算法,并提供了详细的代码示例。

被折叠的 条评论
为什么被折叠?



