/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ class Solution { public: /** * * @param root TreeNode类 * @return int整型 */ int run(TreeNode* root) { // write code here if (root == nullptr) return 0; std::queue<std::pair<TreeNode*, int>> q; q.push({root, 1}); // 节点和深度 while (!q.empty()) { auto [node, depth] = q.front(); q.pop(); // 检查是否是叶子节点 if (node->left == nullptr && node->right == nullptr) { return depth; } if (node->left != nullptr) { q.push({node->left, depth + 1}); } if (node->right != nullptr) { q.push({node->right, depth + 1}); } } return 0; // 不会到达这里 } };