方法1:DFS (递归)
时间复杂度:O(n)
空间复杂度:O(H)
解题思路
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;
}
}