111. Minimum Depth of Binary Tree
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.
解法
dfs,找到叶子结点,再对叶子结点的深度比较,找出深度最小的深度。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private int min = Integer.MAX_VALUE;
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
helper(root, 1);
return min;
}
public void helper(TreeNode root,int depth) {
if (root.left == null && root.right == null) {
min = Math.min(min, depth);
}
if (root.left != null) {
helper(root.left, depth + 1);
}
if (root.right != null) {
helper(root.right, depth + 1);
}
}
}