思路:
// @Title: 二叉树的最小深度 (Minimum Depth of Binary Tree)
// @Author: qisiii
// @Date: 2024-09-14 23:42:57
// @Runtime: 10 ms
// @Memory: 61.4 MB
// @comment:
// @flag:
/**
* 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;
* }
* }
*/
class Solution {
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
int left = minDepth(root.left);
int right = minDepth(root.right);
// 如果左子树或者右子树为0,那得以不为空的那棵树为准
if (left == 0 || right == 0) {
return left + right + 1;
}
return Math.min(left, right) + 1;
}
}
思路:
// @Title: 二叉树的最小深度 (Minimum Depth of Binary Tree)
// @Author: qisiii
// @Date: 2024-01-14 19:59:44
// @Runtime: 14 ms
// @Memory: 62 MB
// @comment:
// @flag:
/**
* 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;
* }
* }
*/
class Solution {
public int minDepth(TreeNode root) {
if(root==null){
return 0;
}
int left=minDepth(root.left);
int right=minDepth(root.right);
if(left==0){
return 1+right;
}
if(right==0){
return 1+left;
}
return 1+Math.min(left,right);
}
}