题目:https://pintia.cn/problem-sets/994805342720868352/problems/994805365537882112
bool数组赋值问题:https://blog.csdn.net/SmartLoveyu/article/details/100121485?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task

注意点

  1. 这题主要是使用了静态链表
  2. 代码写完找了半天bug,结果发现是isRoot数组的初始赋值问题,默认是赋false值的;下次直接赋值使用vector吧,或者赋false值
  3. 另一个需要记住的是反转链表是后序遍历,先递归两个子再将它们反转。
  4. 感觉今天对先序中序后序层序遍历已经有了一个基本的了解了

代码

  1. #include<algorithm>
  2. #include<iostream>
  3. #include<queue>
  4. #include<cstdio>
  5. #include<cstring>
  6. using namespace std;
  7. const int maxn = 110;
  8. struct Node{
  9. int lchild, rchild;
  10. }node[maxn];
  11. int n;
  12. vector<bool> isRoot(maxn, true);
  13. int strToNum(char c){
  14. if(c == '-') return -1;
  15. else {
  16. isRoot[c - '0'] = false;
  17. return c - '0';
  18. }
  19. }
  20. int find_root(){
  21. for(int i = 0; i < n; i++){
  22. if(isRoot[i] == true){
  23. return i;
  24. }
  25. }
  26. }
  27. void invert(int root){
  28. if(root == -1) return;
  29. invert(node[root].lchild);
  30. invert(node[root].rchild);
  31. swap(node[root].lchild, node[root].rchild);
  32. }
  33. void level(int root){
  34. int count = 0;
  35. queue<int> q;
  36. q.push(root);
  37. while(!q.empty()){
  38. int top = q.front();
  39. q.pop();
  40. if (count != 0) printf(" ");
  41. printf("%d",top);
  42. count++;
  43. if(node[top].lchild != -1) q.push(node[top].lchild);
  44. if(node[top].rchild != -1) q.push(node[top].rchild);
  45. }
  46. }
  47. int count_of_in = 0;
  48. void inOrder(int root){
  49. if(root == -1) return;
  50. inOrder(node[root].lchild);
  51. if(count_of_in != 0) printf(" ");
  52. printf("%d",root);
  53. count_of_in++;
  54. inOrder(node[root].rchild);
  55. }
  56. int main(){
  57. char lchild, rchild;
  58. scanf("%d",&n);
  59. for(int i = 0; i < n; i++){
  60. //scanf("%c%c", &lchild, &rchild);
  61. cin>>lchild>>rchild;
  62. node[i].lchild = strToNum(lchild);
  63. node[i].rchild = strToNum(rchild);
  64. }
  65. int root = find_root();
  66. invert(root);
  67. level(root);
  68. cout<<endl;
  69. inOrder(root);
  70. return 0;
  71. }