/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */classSolution {publicintminDepth(TreeNode root) {if (root ==null) {return0; }int left =minDepth(root.left);int right =minDepth(root.right);return (left ==0|| right ==0) ? left + right +1:Math.min(left,right) +1; }}
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int minDepth(TreeNode root) {
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = root, pre = null;
int min = Integer.MAX_VALUE;
while (cur != null || !stack.isEmpty()) {
while (cur != null) {
stack.push(cur);
cur = cur.left;
}
TreeNode node = stack.peek();
if (node.left == null && node.right == null) {
min = Math.min(min, stack.size());
}
if (node.right != null && node.right != pre) {
cur = node.right;
continue;
}
cur = null;
pre = stack.pop();
}
return min == Integer.MAX_VALUE ? 0 : min;
}
}