【1086】Tree Traversals Again (25 分)

举报
野猪佩奇996 发表于 2022/01/23 02:02:22 2022/01/23
【摘要】 #include<iostream>#include<stdio.h>#include<stdlib.h>#include<math.h>#include<string.h>#include<algorithm> #include<map>#inclu...

  
  1. #include<iostream>
  2. #include<stdio.h>
  3. #include<stdlib.h>
  4. #include<math.h>
  5. #include<string.h>
  6. #include<algorithm>
  7. #include<map>
  8. #include<vector>
  9. #include<queue>
  10. #include<stack>
  11. using namespace std;
  12. const int maxn=50;
  13. struct node{
  14. int data;
  15. node* lchild;
  16. node* rchild;
  17. };
  18. int pre[maxn],in[maxn],post[maxn]; //先、中、后序
  19. int n; //结点个数
  20. //当前二叉树的先序序列区间为[preL,preR],中序序列区间为[inL,inR]
  21. //create函数返回构建出的二叉树的根结点地址
  22. node* create(int preL,int preR,int inL,int inR){
  23. if(preL>preR){
  24. return NULL;
  25. }
  26. node* root=new node;//新建一个新的结点,用来存放当前二叉树的根结点
  27. root->data=pre[preL];//新结点的数据域为根结点的值
  28. int k;//这个k不要在for里面定义了,注意有效域
  29. for(k=inL;k<=inR;k++){
  30. if(in[k]==pre[preL]){ //在中序序列中找到in[k]==pre[L]的结点
  31. break;
  32. }
  33. }
  34. int numLeft=k-inL; //左子树的结点个数
  35. //返回左子树的根结点地址,赋值给root的左指针
  36. root->lchild=create(preL+1,preL+numLeft,inL,k-1);
  37. //返回右子树的根结点地址,赋值给root的右指针
  38. root->rchild=create(preL+numLeft+1,preR,k+1,inR);
  39. return root; //返回根结点地址
  40. }
  41. int num=0;//已输出的结点个数
  42. void postorder(node* root){//后序遍历
  43. if(root==NULL){
  44. return;
  45. }
  46. postorder(root->lchild);
  47. postorder(root->rchild);
  48. printf("%d",root->data);
  49. num++;
  50. if(num<n) printf(" ");
  51. }
  52. int main(){
  53. scanf("%d",&n);
  54. char str[5];
  55. stack<int> st;
  56. int x,preIndex=0,inIndex=0; //入栈元素、先序序列位置及中序序列位置
  57. for(int i=0;i<2*n;i++){ //出栈入栈共2n次
  58. scanf("%s",str);
  59. if(strcmp(str,"Push") == 0){ //入栈
  60. scanf("%d",&x);
  61. pre[preIndex++]=x; //令pre[preIndex]=x
  62. st.push(x);
  63. }else{
  64. in[inIndex++]=st.top(); //令in[inIndex]=st.top
  65. st.pop();
  66. }
  67. }
  68. node* root=create(0,n-1,0,n-1); //建树
  69. postorder(root); //后序遍历
  70. system("pause");
  71. return 0;
  72. }

 

文章来源: andyguo.blog.csdn.net,作者:山顶夕景,版权归原作者所有,如需转载,请联系作者。

原文链接:andyguo.blog.csdn.net/article/details/98268828

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。