题目描述
题目难度:Easy
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
Note: A leaf is a node with no children.
AC代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int min = Integer.MAX_VALUE;
public int minDepth(TreeNode root) {
if(root == null) return 0;
helper(root, 1);
return min;
}
private void helper(TreeNode root, int height){
if(root == null) return;
//确定 root 是叶子节点
if(root.left == null && root.right == null)
{
min = Math.min(min, height);
return;
}
helper(root.left, height + 1);
helper(root.right, height + 1);
}
}