题目
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明: 叶子节点是指没有子节点的节点。
示例
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最小深度 2.
解题
思路
这道题是一道简单的二叉树问题,解决方式有两种,递归和利用队列进行迭代。
递归
递归的时候带着当前的层级,如果出现了左右节点都为空的节点,暂时把其层级定义成最小路径,然后继续迭代其他可能,但是如果我们已经有一个最小路径了,其他的迭代就没有必要超过这个最小路径了,适当的终止递归。
迭代
定义一个队列,每一次迭代一层的数据,看看有没有左右节点都为空的元素,有的话,这层就是最短路径。
实测下来递归的方案效率更高,代码可击败100%
代码
递归
class Solution {
int minDepth = 0;
public int minDepth(TreeNode root) {
if (root == null) {
return minDepth;
}
get(root, 1);
return minDepth;
}
public void get(TreeNode root, int level) {
if (root.left == null && root.right == null) {
if (minDepth == 0) {
minDepth = level;
} else {
minDepth = level < minDepth ? level : minDepth;
}
}
if (root.left != null && (minDepth == 0 || level < minDepth)) {
get(root.left, level + 1);
}
if (root.right != null && (minDepth == 0 || level < minDepth)) {
get(root.right, level + 1);
}
}
}
迭代
import javafx.util.Pair;
class Solution {
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
Queue<Pair<TreeNode, Integer>> queue = new LinkedList<>();
queue.add(new Pair<>(root, 1));
Pair<TreeNode, Integer> temp;
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
temp = queue.poll();
if (temp.getKey().left == null && temp.getKey().right == null) {
return temp.getValue();
}
if (temp.getKey().left != null) {
queue.add(new Pair<TreeNode, Integer>(temp.getKey().left, temp.getValue() + 1));
}
if (temp.getKey().right != null) {
queue.add(new Pair<TreeNode, Integer>(temp.getKey().right, temp.getValue() + 1));
}
}
}
return 0;
}
}