一:题目
二:上码
/**
* 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 {
public:
int minDepth(TreeNode* root) {
//思路:当我们遍历其(左右)孩子的节点为空的时候,这时候就到了叶节点,也就是最小的时候
queue<TreeNode*>q;
if(root) q.push(root);
int minDepth = 0;
while(!q.empty()) {
int size = q.size();
minDepth++;
for(int i = 0; i < size; i++) {
TreeNode* node = q.front();
q.pop();
if(node->left) q.push(node->left);
if(node->right) q.push(node->right);
if(node->left == NULL && node->right == NULL)
return minDepth;
}
}
return minDepth;
}
};