原题链接:111.Minimum Depth of Binary Tree
【补充】
【思路】
采用 dfs深度优先:
public int minDepth(TreeNode root) {
if (root == null) return 0;
if (root.left != null && root.right != null) //当根左右均不为空时,遍历左右子树,取最小值
return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
return Math.max(minDepth(root.left), minDepth(root.right)) + 1; //当左右子树有一边为空时,要去最大值
}
41 / 41
test cases passed. Runtime: 1 ms Your runtime beats 12.17% of javasubmissions.
【补充】
采用 bfs 非递归实现:
public int minDepth(TreeNode root) {
if (root == null) return 0;
Queue<TreeNode> queue = new LinkedList<TreeNode>();
int layer = 1;
queue.add(root);
while (!queue.isEmpty()) {
int curCount = queue.size(); //本层节点数
while (curCount-- > 0) { //将下一层节点存入 queue 中
TreeNode temp = queue.poll();
if (temp.left == null && temp.right == null) return layer;
if (temp.left != null) queue.add(temp.left);
if (temp.right != null) queue.add(temp.right);
}
layer++;
}
return layer;
}
41 / 41
test cases passed. Runtime: 1 ms Your runtime beats 12.17% of javasubmissions.