计算根节点到叶子节点的距离,取最小
/**
* 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 {
private int minn = Integer.MAX_VALUE;
public void getMinDepth(TreeNode root, int depth){
if (root.left == null && root.right == null){
minn = Math.min(minn, depth);
return ;
}
if (root.left != null)
getMinDepth(root.left, depth + 1);
if (root.right != null)
getMinDepth(root.right, depth + 1);
}
public int minDepth(TreeNode root) {
// 是个树,就判空
if (root == null) return 0;
getMinDepth(root, 1);
return minn;
}
}