层次遍历算法遍历二叉树c++
时间: 2023-12-02 08:42:43 浏览: 97
以下是C++实现二叉树层次遍历的代码示例:
```c++
#include <iostream>
#include <queue>
using namespace std;
// 二叉树结点的定义
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
// 层次遍历函数
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> res;
if (!root) {
return res;
}
queue<TreeNode*> q{{root}};
while (!q.empty()) {
vector<int> oneLevel;
for (int i = q.size(); i > 0; --i) {
TreeNode* t = q.front(); q.pop();
oneLevel.push_back(t->val);
if (t->left) {
q.push(t->left); }
if (t->right) {
q.push(t->right);
}
}
res.push_back(oneLevel);
}
return res;
}
// 测试
int main() {
TreeNode* root = new TreeNode(3);
root->left = new TreeNode(9);
root->right = new TreeNode(20); root->right->left = new TreeNode(15);
root->right->right = new TreeNode(7);
vector<vector<int>> res = levelOrder(root);
for (auto& level : res) {
for (auto& val : level) {
cout << val << " ";
}
cout << endl;
}
return 0;
}
```
阅读全文