/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int minDepth(TreeNode* root) {
if (root == nullptr) return 0;
if (root->left != nullptr && root->right == nullptr) return minDepth(root->left) + 1;
if (root->right != nullptr && root->left == nullptr) return minDepth(root->right) + 1;
return min(minDepth(root->left), minDepth(root->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) {
if (root == null) {
return 0;
}
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;
}
}