题目描述
代码
public class Code_111 {
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 min_depth = Integer.MAX_VALUE;
//考虑特殊情况
if (root.left != null) min_depth = Math.min(minDepth(root.left), min_depth);
if (root.right != null) min_depth = Math.min(minDepth(root.right), min_depth);
return min_depth + 1;
}
}
思路
递归查找,通过标志数int min_depth = Integer.MAX_VALUE;进行比较,同时得注意特殊情况,左子树,或者右子树不存在的情况,然后左右分别进行递归 if (root.left != null) min_depth = Math.min(minDepth(root.left), min_depth);if (root.right != null) min_depth = Math.min(minDepth(root.right), min_depth);