LeetCode 111. 二叉树的最小深度
原题链接
简单
作者:
caichuntao
,
2023-06-26 13:48:52
,
所有人可见
,
阅读 83
方法1:DFS (递归)
时间复杂度:$O(n)$
空间复杂度:$O(H)$
解题思路
https://leetcode.cn/problems/minimum-depth-of-binary-tree/solution/er-cha-shu-de-zui-xiao-shen-du-by-leetcode-solutio/
Java 代码
/**
* 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) {
int min_depth = Integer.MAX_VALUE;
if (root == null) {
return 0;
}
if (root.left == null && root.right == null) {
return 1;
}
if (root.left != null) {
min_depth = Math.min(min_depth, minDepth(root.left));
}
if (root.right != null) {
min_depth = Math.min(min_depth, minDepth(root.right));
}
return min_depth + 1;
}
}