终于是一道简单的题目了,是为了让大家周末愉快吗^_^
思考过程:
第一反应是用递归处理,然后需要分情况。1.树是空,返回0;2.两个节点都为空,返回1;3.树左节点为空,返回1+右节点最小深度;4.右节点为空,返回1+左节点最小深度;5.两个节点都不为空,返回左节点最小深度和右节点最小深度的最小值再+1。
代码实现:
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
if (root.left == null && root.right == null) {
return 1;
}
if (root.left == null) {
return 1 + minDepth(root.right);
}
if (root.right == null) {
return 1 + minDepth(root.left);
}
return 1 + Math.min(minDepth(root.left), minDepth(root.right));
}
执行结果:
算法复杂度分析:
时间复杂度:O(n),其中 n是树节点数。
空间复杂度:O(1)。
官方提供了两张解法,深度优先和广度优先,我个人思路是属于深度优先,代码实现上,官方深度度优先代码和我个人实现的差不多,就不再赘述,以下是官方广度优先代码:
class QueueNode {
TreeNode node;
int depth;
public QueueNode(TreeNode node, int depth) {
this.node = node;
this.depth = depth;
}
}
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
Queue<QueueNode> queue = new LinkedList<QueueNode>();
queue.offer(new QueueNode(root, 1));
while (!queue.isEmpty()) {
QueueNode nodeDepth = queue.poll();
TreeNode node = nodeDepth.node;
int depth = nodeDepth.depth;
if (node.left == null && node.right == null) {
return depth;
}
if (node.left != null) {
queue.offer(new QueueNode(node.left, depth + 1));
}
if (node.right != null) {
queue.offer(new QueueNode(node.right, depth + 1));
}
}
return 0;
}
执行结果:
总结:
这题是树相关的问题中,比较简单的类型,但是就是这么简单的题目,我在解题过程中,也没有一下子就把所有情况分清楚,导致前面几次提交都是错误的,如下。。。对待有把握的简单题目,还是不能大意,要多加思考。