c++二叉树的层序遍历
时间: 2023-08-06 22:05:55 浏览: 116
二叉树的层序遍历可以使用队列来实现。具体步骤如下:
1. 首先创建一个队列,将根节点入队
2. 当队列不为空时,依次出队队首元素,并将其左右子节点入队
3. 将出队的节点值存储到结果数组中
4. 重复执行步骤2和步骤3,直到队列为空
以下是 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) {}
};
void levelOrder(TreeNode* root) {
if (root == NULL) {
return;
}
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
TreeNode* curr = q.front();
q.pop();
cout << curr->val << " ";
if (curr->left != NULL) {
q.push(curr->left);
}
if (curr->right != NULL) {
q.push(curr->right);
}
}
}
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);
root->right->left = new TreeNode(6);
root->right->right = new TreeNode(7);
levelOrder(root);
return 0;
}
```
输出结果为:1 2 3 4 5 6 7
阅读全文