leetcode T111
记录
本来没想着发布这题的,但是前两天做到这题的时候,发现自己完全忘了,记不起解题思路了,因此重新写两遍,加深下印象
题目要求
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明:叶子节点是指没有子节点的节点。
示例 1:
输入:root = [3,9,20,null,null,15,7]
输出:2
示例 2:
输入:root = [2,null,3,null,4,null,5,null,6]
输出:5
提示:
树中节点数的范围在 [0, 105] 内
-1000 <= Node.val <= 1000
已有设置
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
两种方法里面,迭代法更简单,递归法相对难想到一点,前者就是直接用层序遍历,第一个遇到的左右子节点都为空的情况即为最小深度。递归法相对麻烦的就是不像迭代法直接把过程梳理完,它其实是隐式栈。
递归法它并不像迭代法那样,遇到就直接可以返回结果,它需要对每一个都要进行比较。
递归法
// 第一种
public int minDepth(TreeNode root) {
if (root == null) return 0;
if (root.left == null && root.right == null)
return 1;
int minDepth = Integer.MAX_VALUE;
if (root.left != null) {
minDepth = Math.min(minDepth(root.left), minDepth);
}
if (root.right != null) {
minDepth = Math.min(minDepth(root.right), minDepth);
}
return minDepth + 1;
}
// 第二种
public int minDepth(TreeNode root) {
if (root == null) return 0;
if (root.left == null && root.right == null)
return 1;
int l = minDepth(root.left);
int r = minDepth(root.right);
if (root.left == null || root.right == null) {
return l + r + 1;
}
return Math.min(l, r) + 1;
}
迭代法
public int minDepth(TreeNode root) {
Deque<TreeNode> queue = new LinkedList<>();
if (root != null)
queue.offer(root);
int level = 0;
while (!queue.isEmpty()) {
int size = queue.size();
level++;
for (int i = 0; i < size; i++) {
TreeNode temp = queue.poll();
if (temp.left != null) {
queue.offer(temp.left);
}
if (temp.right != null) {
queue.offer(temp.right);
}
if (temp.left == null && temp.right == null) {
return level;
}
}
}
return level;
}