题目链接
思路:找到所有的叶子节点,然后从叶子节点开始向上遍历,计算深度。
递归思路:将当前的节点分别找到两边的深度大小,然后进行比较,找到最小值之后,将最小值+1返回。
/**
* 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) {
// return getMinDepth(root);
return minDepth1(root);
}
// 1.我的代码
public int getMinDepth(TreeNode node) {
if(node == null) return 0;
int left = getMinDepth(node.left);
int right = getMinDepth(node.right);
if(node.left == null && node.right != null) {
return 1 + right;
}
if(node.left != null && node.right == null) {
return 1 + left;
}
return 1 + (left > right ? right : left);
}
// 2.老师的代码
public int minDepth1(TreeNode root) {
if(root == null) return 0;
if(root.left == null && root.right == null) return 1; // 当前只有一个节点
int min = Integer.MAX_VALUE;
if(root.left != null) {
min = Math.min(minDepth(root.left), min);
}
// 这里不能使用else进行连接起来,否则的话会发生右边是空的话,就会一直获取的值为0
if(root.right != null) {
min = Math.min(minDepth(root.right), min);
}
return min+1;
}
}