鱼C论坛

 找回密码
 立即注册
查看: 2459|回复: 0

[技术交流] PTA A_1102 Invert a Binary Tree

[复制链接]
发表于 2020-2-11 16:52:58 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
传送门:https://pintia.cn/problem-sets/9 ... /994805365537882112

解:
二叉树的遍历
  1. #include<cstdio>
  2. #include<cstring>
  3. #include<queue>

  4. using namespace std;

  5. typedef struct node{
  6.     int lchild, rchild;
  7. } BTNode;

  8. int ttl;

  9. void reverse_tree(int root, BTNode tree[])
  10. {
  11.     if (root == -1) return;

  12.     reverse_tree(tree[root].lchild, tree);
  13.     reverse_tree(tree[root].rchild, tree);
  14.    
  15.     int temp = tree[root].lchild;
  16.     tree[root].lchild = tree[root].rchild;
  17.     tree[root].rchild = temp;
  18. }

  19. void BFS(int root, BTNode tree[])
  20. {
  21.     queue<int> q;

  22.     q.push(root);

  23.     while (!q.empty())
  24.     {
  25.         int index = q.front();
  26.         q.pop();

  27.         printf("%d", index);
  28.         if (--ttl) putchar(' ');

  29.         if (tree[index].lchild != -1) q.push(tree[index].lchild);
  30.         if (tree[index].rchild != -1) q.push(tree[index].rchild);
  31.     }

  32.     putchar('\n');
  33. }

  34. void print_inorder(int root, BTNode tree[])
  35. {
  36.     if (root == -1) return;

  37.     print_inorder(tree[root].lchild, tree);
  38.     printf("%d", root);
  39.     if (--ttl) putchar(' ');
  40.     print_inorder(tree[root].rchild, tree);
  41. }

  42. int main(void)
  43. {
  44.     int n, hash_table[15] = {0};
  45.     BTNode tree[15];

  46.     memset(tree, -1, sizeof(tree));
  47.    
  48.     scanf("%d", &n);
  49.     if (!n) return 0;
  50.     getchar();
  51.     for (int i = 0; i < n; i++)
  52.     {
  53.         char s[5];

  54.         fgets(s, 5, stdin);
  55.         if (s[0] != '-') ++hash_table[tree[i].lchild = s[0] - '0'];
  56.         if (s[2] != '-') ++hash_table[tree[i].rchild = s[2] - '0'];
  57.     }

  58.     for (int i = 0; i < n; i++)
  59.         if (!hash_table[i])
  60.         {
  61.             reverse_tree(i, tree);
  62.             ttl = n;
  63.             BFS(i, tree);
  64.             ttl = n;
  65.             print_inorder(i, tree);
  66.             break;
  67.         }

  68.     return 0;
  69. }
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-7-8 01:51

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表