二叉树的层序遍历c++
时间: 2023-11-05 21:03:13 浏览: 105
二叉树的层序遍历可以使用广度优先搜索(BFS)实现。具体步骤如下:
1. 新建一个队列,将根节点入队;
2. 当队列不为空时,循环执行以下步骤:
a. 取出队首节点,将其值存入结果数组中;
b. 如果该节点有左子节点,将左子节点入队;
c. 如果该节点有右子节点,将右子节点入队;
3. 返回结果数组。
以下是C++代码实现:
```c++
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
//二叉树节点的定义
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
vector<int> levelOrder(TreeNode* root) {
vector<int> res;
if (!root) return res;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
TreeNode* cur = q.front();
q.pop();
res.push_back(cur->val);
if (cur->left) q.push(cur->left);
if (cur->right) q.push(cur->right);
}
return res;
}
int main() {
//创建一棵二叉树
TreeNode* root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->left->right = new TreeNode(5);
//层序遍历并输出结果
vector<int> res = levelOrder(root);
for (int i = 0; i < res.size(); i++) {
cout << res[i] << " ";
}
cout << endl;
return 0;
}
```
输出结果为:1 2 3 4 5
阅读全文