前序和后序之所以不确定一棵树的原因就是当只有一棵子树的时候,不确定是左子树还是右子树。找前序的第二个结点在后续中位置,左边就是左子树。递归建树
要是到最后一个位置还没找出根节点,那么区分不了左右,标志位标记false
#include<iostream>
#include<vector>
#include<queue>
#include<stack>
#include<string>
using namespace std;
const int maxn = 50;
struct node
{
int data;
node* lchild;
node* rchild;
};
int pre[maxn], post[maxn];
int n;
bool isUnique = true;
node* create(int prel, int prer, int postl, int postr)
{
if (prel > prer)
return NULL;
node* root = new node;
root->data = pre[prel];
int i, numLeft = 0;
for (i = postl;i <postr; i++)
{
numLeft++;
if (post[i] == pre[prel + 1])
break;
}
if (i == postr - 1)
isUnique = false;
root->lchild = create(prel + 1, prel + numLeft, postl,i);
root->rchild = create(prel + numLeft+1, prer, i + 1, postr - 1);
return root;
}
int flag = 1;
void inorder(node* root)
{
if (root == NULL)
return;
inorder(root->lchild);
if (flag)
{
cout << root->data;
flag = 0;
}
else
cout << " " << root->data;
inorder(root->rchild);
}
int main()
{
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> pre[i];
}
for (int i = 0; i < n; i++)
{
cin >> post[i];
}
node* root = create(0, n - 1, 0, n - 1);
if (isUnique)
{
cout << "Yes" << endl;
inorder(root);
cout << endl;
}
else
{
cout << "No" << endl;
inorder(root);
cout << endl;
}
}