思路:
只讲解如何通过中序后序遍历序列来构建二叉树:假设递归的过程中某部的后序序列区间为[postL,postR],中序序列的区间为[inL, inR],那么由后序序列的性质可知,后序序列的最后一个元素post[postR]即为根节点。那么,我们在中序序列中找到一个位置i,使得in[i]==post[postR],这样就找到了中序序列的根节点。那么锁子书中的节点的个数numLeft=i-inL,于是左子树的后序序列区间为[postL,postL+numLeft-1],左子树的中序序列区间为[inL, k-1]; 右子树的后序序列区间为[postL+numLeft,postR-1],右子树的中序序列区间为[i+1,inR]。
#include <iostream>
#include <cstdio>
#include <stack>
#include <algorithm>
using namespace std;
const int maxn = 50;
struct node
{
int data;
node* lchild;
node* rchild;
};
int pre[maxn], in[maxn], post[maxn];
int n;
node* create(int postl, int postr, int inl, int inr);
void preorder(node* root);
int main() {
int n;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> post[i];
}
for (int i = 0; i < n; i++) {
cin >> in[i];
}
node* root = create(0, n-1, 0, n-1);
preorder(root);
}
node* create(int postl, int postr, int inl, int inr) {
if (postl > postr) {
return NULL;
}
node* root = new node;
root->data = post[postr];
int i = inl;
for (i=inl; i <= inr; i++) {
if (in[i] == post[postr]) {
break;
}
}
int inleftnumber = i-inl;
root->lchild = create(postl, postl + inleftnumber -1, inl, i -1);
root->rchild = create(postl + inleftnumber, postr - 1, i + 1, inr);
return root;
}
void preorder(node* root) {
if (root == NULL) {
return;
}
cout << root->data<<" ";
preorder(root->lchild);
preorder(root->rchild);
}
同理,根据二叉树的前序,中序,也可以确定一颗唯一的二叉树:
node* create(int preL, int preR, int inL, int inR) {
if (preL>preR)
{
return NULL;
}
node* root = new node;
root->data = pre[preL];
int i;
for (i = inL; i < inR; i++)
{
if (in[i]==root->data)
{
break;
}
}
int numsleft = i - inL;
root->lchild = create(preL + 1, preL + numsleft, inL, i - 1);
root->rchild = create(preL + numsleft + 1, preR, i + 1, inR);
return root;
}