题目:
代码(首刷自解 2024年1月24日):
class Solution {
public:int minDepth(TreeNode* root) {if(root == nullptr) return 0;queue<TreeNode*> que;TreeNode* cur = root;que.push(cur);int size = 0;int depth = 0;while (!que.empty()) {size = que.size();int flag = size - 1;while (size--){if (size == flag) depth++;TreeNode* node = que.front();que.pop();if ((!node->left) && (!node->right)) return depth;if (node->left) que.push(node->left);if (node->right) que.push(node->right);}}return depth;}
};
首刷看解析 迭代 2024年1月25日
class Solution {
public:int minDepth(TreeNode* root) {if (root == nullptr) return 0;if (root->left == nullptr && root->right != nullptr) {return minDepth(root->right) + 1;}if (root->left != nullptr && root->right == nullptr) {return minDepth(root->left) + 1;}return min(minDepth(root->left), minDepth(root->right)) + 1;}
};