解题思路
深度优先搜索。
相关代码
/**
* 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) {
int res = 1000000;
if(root==null) return 0;
if(root.left!=null)
res = Math.min(minDepth(root.left)+1,res);
if(root.right!=null)
res = Math.min(minDepth(root.right)+1,res);
if(res==1000000) res=1;
return res;
}
}