LeetCode 111 Minimum Depth of Binary Tree
概述
https://leetcode.com/problems/minimum-depth-of-binary-tree/
宽度优先搜索
while 循环 + 队列,同时记录节点指针和对应深度。
被 LeetCode 用一个空指针偷袭了,我没防住。。。
class Solution {
public:
int minDepth(TreeNode* root) {
if (!root) return 0;
queue<pair<TreeNode*, int>> q;
q.push({root, 1});
while (!q.empty()) {
auto c = q.front();
q.pop();
if (!c.first->left && !c.first->right) {
return c.second;
}
if (c.first->left) {
q.push({c.first->left, c.second + 1});
}
if (c.first->right) {
q.push({c.first->right, c.second + 1});
}
}
return -1;
}
};