PAT (Advanced Level) Practice 1086 Tree Traversals Again

朴灿烈づ我的快乐病毒、 2023-07-03 07:27 95阅读 0赞

根据操作写递归就行了,注意一点,data不是从1到n顺序来的,所以要自己去获取push后面的数字,不能简单的用计数器++。

  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. #include <stdio.h>
  5. using namespace std;
  6. struct node{
  7. node* lchild;
  8. node* rchild;
  9. int data;
  10. };
  11. vector<int> v;
  12. string op[100];
  13. int index=0,n;
  14. node* createTree(){
  15. if(index>=2*n) return NULL;
  16. if(op[index][1]=='u'){//push
  17. node* root = new node;
  18. string s = op[index];
  19. s.erase(0,5);
  20. int sum=0;
  21. for(int i=0;i<s.size();i++){
  22. sum=sum*10 + s[i]-'0';
  23. }
  24. root->data=sum;
  25. index++;
  26. root->lchild=createTree();
  27. root->rchild=createTree();
  28. return root;
  29. }else{
  30. index++;
  31. return NULL;
  32. }
  33. }
  34. void posttravel(node* root){
  35. if(root!=NULL){
  36. posttravel(root->lchild);
  37. posttravel(root->rchild);
  38. v.push_back(root->data);
  39. }
  40. }
  41. int main()
  42. {
  43. cin>>n;
  44. getchar();
  45. for(int i=0;i<2*n;i++){
  46. getline(cin,op[i]);
  47. }
  48. node* root = createTree();
  49. posttravel(root);
  50. for(int i=0;i<v.size();i++){
  51. cout<<v[i];
  52. if(i!=v.size()-1) cout<<" ";
  53. }
  54. return 0;
  55. }

发表评论

表情:
评论列表 (有 0 条评论,95人围观)

还没有评论,来说两句吧...

相关阅读