根据中序遍历和后序遍历输出前序遍历的数据结构完整代码
时间: 2024-05-28 07:06:34 浏览: 86
Python二叉树的遍历操作示例【前序遍历,中序遍历,后序遍历,层序遍历】
5星 · 资源好评率100%
根据中序遍历和后序遍历输出前序遍历的数据结构完整代码如下:
```
#include<iostream>
#include<cstring>
using namespace std;
const int maxn = 100;
struct Node {
int data;
Node *lchild, *rchild;
};
int n;
int postorder[maxn], inorder[maxn];
Node* create(int postL, int postR, int inL, int inR) {
if(postL > postR) {
return NULL;
}
Node* root = new Node;
root->data = postorder[postR];
int k;
for(k = inL; k <= inR; k++) {
if(inorder[k] == postorder[postR]) {
break;
}
}
int numLeft = k - inL;
root->lchild = create(postL, postL + numLeft - 1, inL, k - 1);
root->rchild = create(postL + numLeft, postR - 1, k + 1, inR);
return root;
}
int num = 0;
void preOrder(Node* root) {
if(root == NULL) {
return;
}
cout << root->data;
num++;
if(num < n) {
cout << " ";
} else {
cout << endl;
}
preOrder(root->lchild);
preOrder(root->rchild);
}
int main() {
cin >> n;
for(int i = 0; i < n; i++) {
cin >> postorder[i];
}
for(int i = 0; i < n; i++) {
cin >> inorder[i];
}
Node* root = create(0, n - 1, 0, n - 1);
preOrder(root);
return 0;
}
```
阅读全文