/**
* 111. Minimum Depth of Binary Tree
* 1. Time:O(n) Space:O(h)
* 2. Time:O(n) Space:O(h)
*/
// 1. Time:O(n) Space:O(h)
class Solution {
public int minDepth(TreeNode root) {
if(root==null) return 0;
if(root.left==null && root.right==null) return 1;
int min = Integer.MAX_VALUE;
if(root.left!=null)
min = Math.min(minDepth(root.left),min);
if(root.right!=null)
min = Math.min(minDepth(root.right),min);
return min+1;
}
}
// 2. Time:O(n) Space:O(h)
class Solution {
public int minDepth(TreeNode root) {
if(root==null) return 0;
Stack<TreeNode> stack = new Stack<>();
TreeNode last = null;
int level=0,minLevel=Integer.MAX_VALUE;
while(root!=null || !stack.isEmpty()){
while(root!=null){
stack.push(root);
level++;
root = root.left;
}
TreeNode tmp = stack.peek();
if(tmp.right!=null && tmp.right!=last)
root = tmp.right;
else{
if(tmp.left==null && tmp.right==null)
minLevel = Math.min(minLevel,level);
last = stack.pop();
level--;
}
}
return minLevel;
}
}