已知二叉树的先序序列,输出层序遍历序列。
时间: 2023-12-08 12:35:52 浏览: 80
二叉树先序和中序求后序
根据二叉树的层序遍历的特点,我们可以使用队列来实现。具体步骤如下:
1. 将先序序列转化为中序序列。
2. 根据中序序列构建二叉树。
3. 将根节点入队。
4. 当队列不为空时,取出队首元素,输出该节点的值,并将其左右子节点入队。
5. 重复步骤4,直到队列为空。
下面是代码示例:
```
#include <iostream>
#include <queue>
#include <unordered_map>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder, int preStart, int preEnd, int inStart, int inEnd, unordered_map<int, int>& map) {
if (preStart > preEnd) {
return NULL;
}
int rootVal = preorder[preStart];
int rootIndex = map[rootVal];
int leftSize = rootIndex - inStart;
TreeNode* root = new TreeNode(rootVal);
root->left = buildTree(preorder, inorder, preStart + 1, preStart + leftSize, inStart, rootIndex - 1, map);
root->right = buildTree(preorder, inorder, preStart + leftSize + 1, preEnd, rootIndex + 1, inEnd, map);
return root;
}
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;
}
vector<int> preorderToLevelOrder(vector<int>& preorder, vector<int>& inorder) {
unordered_map<int, int> map;
for (int i = 0; i < inorder.size(); i++) {
map[inorder[i]] = i;
}
TreeNode* root = buildTree(preorder, inorder, 0, preorder.size() - 1, 0, inorder.size() - 1, map);
return levelOrder(root);
}
int main() {
vector<int> preorder = {1, 2, 4, 5, 3, 6, 7};
vector<int> inorder = {4, 2, 5, 1, 6, 3, 7};
vector<int> levelorder = preorderToLevelOrder(preorder, inorder);
for (int i = 0; i < levelorder.size(); i++) {
cout << levelorder[i] << " ";
}
return 0;
}
```
阅读全文