题目描述
求给定二叉树的最小深度。最小深度是指树的根结点到最近叶子结点的最短路径上结点的数量。
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.
这题首先题目就很明确的告诉我们,这是一道树题。树题一般有两种解法常规解法,dfs和bfs。这题我们可以看到是需要我们找"深度"相关,所以我们运用dfs。其次,我们可以发现,他需要找最小深度,所以我们记住,我们只需要对比所有叶节点的depth,即既无左孩子,也无右孩子的节点的depth,而不是所有节点的depth。
整体分三步:
- 检测当前的根节点是否为空,为空则压根没有最小深度return null,如果不为空,我们新建一个arraylist储存所有叶节点的depth,同时我们从根节点开始dfs(call DFS function).
- DFS function 内,我们首先需要检测当前收到的节点是不是叶节点,如果是,我们就把他的深度放进arraylist里。如果不是叶节点,我们继续用dfs循环往下找他的左孩子和右孩子。
- 我们return回arraylist的最小值,这便是二叉树的最小深度。
具体代码如下:
/**
import java.util.*;
public class Solution {
public int run(TreeNode root) {
ArrayList<Integer> holder = new ArrayList<>();
if(root == null){
return 0;
}
DFS(root,1,holder);
return Collections.min(holder);
}
public void DFS(TreeNode root,int depth,ArrayList<Integer> holder){
if(root.left == null && root.right == null){
holder.add(depth);
}
if(root.left != null){
DFS(root.left,depth+1,holder);
}
if(root.right != null){
DFS(root.right,depth+1,holder);
}
}
}
京公网安备 11010502036488号