完全二叉树的层序遍历c++
时间: 2023-12-11 20:33:26 浏览: 92
C语言编程之完全二叉树的层序遍历
以下是完全二叉树的层序遍历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<int> levelOrder(TreeNode* root) {
vector<int> res;
if (!root) {
return res;
}
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
int size = q.size();
for (int i = 0; i < size; i++) {
TreeNode* node = q.front();
q.pop();
res.push_back(node->val);
if (node->left) {
q.push(node->left);
}
if (node->right) {
q.push(node->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);
root->right->left = new TreeNode(6);
root->right->right = new TreeNode(7);
vector<int> res = levelOrder(root);
for (int i = 0; i < res.size(); i++) {
cout << res[i] << " ";
}
return 0;
}
```
阅读全文