题目:https://pintia.cn/problem-sets/994805342720868352/problems/994805485033603072
这道题算是入门题了吧,后序和中序建立二叉树,再用BFS层序遍历,记录一下自己的几个问题

  1. 建立二叉树的时候一定要写出左子树的个数变量,一开始用自己的写法发现程序运行不正常,一定要定义numLeft = i - inL,然后看一下root的左右子树的建立范围
  2. BFS的时候不要忘了在获得队首元素后将它pop

代码

  1. #include<algorithm>
  2. #include<iostream>
  3. #include<queue>
  4. using namespace std;
  5. vector<int> post, in;
  6. struct node{
  7. int data;
  8. node* leftchild;
  9. node* rightchild;
  10. };
  11. node* create(int postL, int postR, int inL, int inR){
  12. if(postL > postR) return NULL;
  13. node* root = new node;
  14. root->data = post[postR];
  15. int i;
  16. for(i = inL; i <= inR; i++){
  17. if(in[i] == post[postR]) break;
  18. }
  19. int numLeft = i - inL;
  20. root->leftchild = create(postL, postL + numLeft - 1, inL, i - 1);
  21. root->rightchild = create(postL + numLeft, postR - 1, i + 1, inR);
  22. return root;
  23. }
  24. int main(){
  25. int n;
  26. scanf("%d",&n);
  27. post.resize(n), in.resize(n);
  28. for(int i = 0; i < n; i++) scanf("%d", &post[i]);
  29. for(int i = 0; i < n; i++) scanf("%d", &in[i]);
  30. node* root = create(0, n - 1, 0, n - 1);
  31. queue<node*> q;
  32. q.push(root);
  33. while(!q.empty()){
  34. node * top = q.front();
  35. q.pop();
  36. printf("%d", top->data);
  37. if(top->leftchild != NULL) q.push(top->leftchild);
  38. if(top->rightchild != NULL) q.push(top->rightchild);
  39. if(q.size() != 0) printf(" ");
  40. }
  41. return 0;
  42. }