dfs
与求最大深度一致,不过要判断特殊情况
class Solution {
public int minDepth(TreeNode root) {
if (root == null) return 0; //输入[]特判
//两边都为null
if (root.left == null && root.right == null) {
return 1;
}
//注意要考虑一边null一边有的情况
if (root.left == null && root.right != null) {
return minDepth(root.right) + 1;
}
//注意要考虑一边null一边有的情况
if (root.right == null && root.left != null) {
return minDepth(root.left) + 1;
}
// if (root.left != null && root.right != null) {}
int left = minDepth(root.left);
int right = minDepth(root.right);
return Math.min(left, right) + 1;
}
}
bfs
当我们找到一个叶子节点时,直接返回这个叶子节点的深度。广度优先搜索的性质保证了最先搜索到的叶子节点的深度一定最小。
class Solution {
// 自定义新node
class Node {
TreeNode node;
int depth; // 节点所在深度
public Node(TreeNode node, int depth) {
this.node = node;
this.depth = depth;
}
}
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
Queue<Node> queue = new LinkedList<>();
queue.offer(new Node(root, 1));
while (!queue.isEmpty()) {
Node node1 = queue.poll(); //自定义的node
TreeNode node = node1.node; // treenode
int depth = node1.depth;// 当前节点深度
if (node.left == null && node.right == null) {
return depth; // 找到的第一个叶子结点
}
if (node.left != null) {
queue.offer(new Node(node.left, depth + 1));
}
if (node.right != null) {
queue.offer(new Node(node.right, depth + 1));
}
}
return 0;
}
}