36 lines
955 B
C++
36 lines
955 B
C++
// https://leetcode.com/problems/minimum-depth-of-binary-tree/
|
|
|
|
/**
|
|
* Definition for a binary tree node.
|
|
*/
|
|
struct TreeNode {
|
|
int val;
|
|
TreeNode *left;
|
|
TreeNode *right;
|
|
TreeNode() : val(0), left(nullptr), right(nullptr) {}
|
|
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
|
|
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
|
|
};
|
|
|
|
class Solution {
|
|
private:
|
|
int min = 100001;
|
|
public:
|
|
int minDepth(TreeNode* root) {
|
|
if (root == nullptr) return 0;
|
|
return minDepth(root, 1);
|
|
}
|
|
int minDepth(TreeNode* root, int current) {
|
|
if (root == nullptr) {
|
|
return min;
|
|
} else {
|
|
if (root->left == nullptr && root->right == nullptr && current < min) {
|
|
min = current;
|
|
}
|
|
minDepth(root->left, current + 1);
|
|
minDepth(root->right, current + 1);
|
|
}
|
|
return min;
|
|
}
|
|
};
|