二叉树的遍历是以DFS和BFS为基础的,无非是在DFS和BFS上面的变形,熟练掌握了BFS和DFS以后,这种类型的题目也就没有什么太大的难度了
题目描述如下:
题目大致意思:
根据二叉树的中序遍历序列,给出树的后续遍历序列。
大致思路:
相当于给出二叉树的先序遍历序列和中序遍历序列,重新构造这颗二叉树,并且输出这颗二叉树的后续遍历序列。压栈的顺序相当于先序遍历序列,出栈的顺序相当于中序遍历序列。
提交结果如下:
提交的代码如下:
#include<iostream>
#include<stack>
#include<string>
using namespace std;
struct Node
{
int data;
Node *lchild,*rchild;
};
int pre_order[30];
int in_order[30];
int n;
int ans=0;
Node *creat_tree(int pre_L,int pre_R,int in_L,int in_R);
void post_order(Node *root);
int main()
{
cin>>n;
stack<int> st;
int index=1;
int j=0,w=0;
for(int i=0;i<n*2;i++)
{
string str;
cin>>str;
if(str=="Pop")
{
in_order[j++]=st.top();
st.pop();
}
else{
int x;
cin>>x;
st.push(x);
pre_order[w++]=x;
}
}
Node *root=creat_tree(0,n-1,0,n-1);
post_order(root);
return 0;
}
void post_order(Node *root) //二叉树的后序遍历序列
{
if(root==NULL)
return;
post_order(root->lchild);
post_order(root->rchild);
if(ans<n-1)
{
cout<<root->data<<" ";
ans++;
}
else
cout<<root->data<<endl;
}
Node *creat_tree(int pre_L,int pre_R,int in_L,int in_R)//根据前序遍历序列和中序遍历序列,重新构建一个二叉树
{
if(pre_L>pre_R||in_L>in_R)
return NULL;
Node *root=new Node;
root->data=pre_order[pre_L];
int temp=pre_order[pre_L];
int k;
for(k=in_L;k<=in_R;k++)
{
if(temp==in_order[k])
break;
}
int left_number=k-in_L;
root->lchild=creat_tree(pre_L+1,pre_L+left_number,in_L,k-1);
root->rchild=creat_tree(pre_L+left_number+1,pre_R,k+1,in_R);
return root;
}
本次提交后累计得分为1569。