求二叉树的最小深度,可以通过深度优先搜索DFS。
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int run(TreeNode root) {
return find_depth(root);
}
public int find_depth( TreeNode root){
if (root == null){
return 0;
}
if(root.left == null && root.right != null){
return 1 + find_depth(root.right);
}
if (root.right == null && root.left != null){
return 1 + find_depth(root.left);
}
return 1 + Math.min(find_depth(root.left), find_depth(root.right));
}
}