Leetcode102. 二叉树的层序遍历
BFS板子,记得判断空的子树不用加
代码:
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> ans;
if (!root)return ans;
queue<TreeNode*>q;
q.push(root);
while (!q.empty()) {
vector<int> tmp;
int size = q.size();
for (int i = 0; i < size; i++) {
TreeNode* p = q.front(); q.pop();
if (p) {
tmp.push_back(p->val);
q.push(p->left);
q.push(p->right);
}
}
if (!tmp.empty())ans.push_back(tmp);
}
return ans;
}
};