已知后续 中序 构建二叉树 并且层序遍历
include<bits/stdc++.h>
using namespace std;
const int N = 100;
int n;
// 定义二叉树结构体
struct Tree {
int x; // 节点的值
Tree* left; // 左子树
Tree* right; // 右子树
};
// 递归打印树的后序遍历(示例)
void pre(Tree* t) {
if (t == nullptr) return;
cout << t->x << " ";
pre(t->left);
pre(t->right);
}
// 递归打印树的中序遍历
void ino(Tree* t) {
if (t == nullptr) return;
ino(t->left);
cout << t->x << " ";
ino(t->right);
}
// 递归打印树的层序遍历
void levelOrder(Tree* root) {
if (root == nullptr) return;
queue<Tree*> q;
q.push(root);
while (!q.empty()) {
Tree* node = q.front();
q.pop();
cout << node->x << " ";
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
}
}
// 从后序和中序遍历重建二叉树
Tree* buildTree(vector
if (inStart > inEnd) return nullptr;
// 后序遍历的最后一个元素是根节点
int rootVal = postorder[postIdx--];
// 创建根节点
Tree* root = new Tree{rootVal, nullptr, nullptr};
// 找到根节点在中序遍历中的位置
int inIdx = -1;
for (int i = inStart; i <= inEnd; i++) {
if (inorder[i] == rootVal) {
inIdx = i;
break;
}
}
// 递归构建右子树和左子树
root->right = buildTree(postorder, inorder, postIdx, inIdx + 1, inEnd);
root->left = buildTree(postorder, inorder, postIdx, inStart, inIdx - 1);
return root;
}
int main() {
cin >> n;
vector<int> postorder(n), inorder(n);
for (int i = 0; i < n; i++) cin >> postorder[i];
for (int i = 0; i < n; i++) cin >> inorder[i];
// 初始的后序遍历索引
int postIdx = n - 1;
// 通过后序和中序遍历构建二叉树
Tree* root = buildTree(postorder, inorder, postIdx, 0, n - 1);
// 输出层序遍历
levelOrder(root);
cout << endl;
return 0;
}
浙公网安备 33010602011771号