public class Solution {
public int minDepth(TreeNode root) {
// Start typing your Java solution below
// DO NOT write main() function
if(root == null) return 0;
if(root.left == null){
return minDepth(root.left)+1;
}
if(root.right == null){
return minDepth(root.right)+1;
}
return findMin(minDepth(root.left),minDepth(root.right)) + 1;// a<b?a:b
}
public int findMin(int a, int b){
return a<b?a:b;
}
}// recursion
int minDepth(TreeNode *root) {
if(!root) return 0;
if(!root -> left) {
return minDepth(root -> right) + 1;
}
if(!root -> right) {
return minDepth(root -> left) + 1;
}
int left = minDepth(root -> left);
int right = minDepth(root -> right);
return (left < right ? left : right) + 1;
}
//c++
public int minDepth(TreeNode root) {
if(root==null)
return 0;
LinkedList<TreeNode> trees=new LinkedList<TreeNode>();
LinkedList<Integer> depth=new LinkedList<Integer>();
int level=1;
trees.add(root);
depth.add(level);
TreeNode top=null;
int curr_depth=0;
while(trees.size()>0)
{
top=trees.remove();
curr_depth=depth.remove();
if(top.left==null && top.right==null)
{
return curr_depth;
}
if(top.left!=null)
{
trees.add(top.left);
depth.add(curr_depth+1);
}
if(top.right!=null)
{
trees.add(top.right);
depth.add(curr_depth+1);
}
}
return curr_depth;
}