题解 | 二叉树的最小深度
二叉树的最小深度
https://www.nowcoder.com/practice/e08819cfdeb34985a8de9c4e6562e724?tpId=46&tqId=29030&rp=1&difficulty=&judgeStatus=&tags=/question-ranking
import java.util.*;
// public class TreeNode {
// int val = 0;
// TreeNode left = null;
// TreeNode right = null;
// }
public class Solution {
/**
*
* @param root TreeNode类
* @return int整型
*/
public int run (TreeNode root) {
ArrayList<Integer> path = new ArrayList<>();
// write code here
if (root == null) {
return 0;
}
DFS(root, 1, path);
return Collections.min(path);
}
public void DFS(TreeNode root, int depth, ArrayList<Integer> path) {
if (root.left != null) {
DFS(root.left, depth + 1, path);
}
if (root.right != null) {
DFS(root.right, depth + 1, path);
}
if (root.left == null && root.right == null) {
path.add(depth);
}
}
}
查看7道真题和解析