1102. Invert a Binary Tree (25)

拼搏现实的明天。 2022-05-30 06:09 253阅读 0赞

The following is from Max Howell @twitter:

Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so fuck off.

Now it’s your turn to prove that YOU CAN invert a binary tree!

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (<=10) which is the total number of nodes in the tree — and hence the nodes are numbered from 0 to N-1. Then N lines follow, each corresponds to a node from 0 to N-1, and gives the indices of the left and right children of the node. If the child does not exist, a “-“ will be put at the position. Any pair of children are separated by a space.

Output Specification:

For each test case, print in the first line the level-order, and then in the second line the in-order traversal sequences of the inverted tree. There must be exactly one space between any adjacent numbers, and no extra space at the end of the line.

Sample Input:

  1. 8
  2. 1 -
  3. - -
  4. 0 -
  5. 2 7
  6. - -
  7. - -
  8. 5 -
  9. 4 6

Sample Output:

  1. 3 7 2 6 4 0 5 1
  2. 6 5 7 4 3 2 0 1

题目大意:

代码:

  1. #include<stdio.h>
  2. #include<queue>
  3. using namespace std;
  4. struct node
  5. {
  6. int flag;
  7. int lchild,rchild;
  8. }tree[20];
  9. int flag=0;
  10. void inorder(int root)
  11. {
  12. //printf("%d\n",root);
  13. if(root!=-1)
  14. {
  15. inorder(tree[root].rchild);
  16. if(flag==0)
  17. {
  18. printf("%d",root);
  19. flag=1;
  20. }
  21. else
  22. {
  23. printf(" %d",root);
  24. }
  25. inorder(tree[root].lchild);
  26. }
  27. }
  28. int tag=0;
  29. void levelorder(int root)
  30. {
  31. queue<int> q;
  32. q.push(root);
  33. while(!q.empty())
  34. {
  35. int tmp=q.front();
  36. q.pop();
  37. if(tmp!=-1)
  38. {
  39. q.push(tree[tmp].rchild);
  40. q.push(tree[tmp].lchild);
  41. if(tag==0)
  42. {
  43. printf("%d",tmp);
  44. tag=1;
  45. }
  46. else
  47. {
  48. printf(" %d",tmp);
  49. }
  50. }
  51. }
  52. }
  53. int main()
  54. {
  55. int i,j,n,m,k,t;
  56. char l[2],r[2];
  57. scanf("%d",&n);
  58. for(i=0;i<n;i++)
  59. {
  60. scanf("%s %s",l,r);
  61. if(l[0]!='-')
  62. {
  63. tree[i].lchild=l[0]-'0';
  64. tree[l[0]-'0'].flag=1;
  65. }
  66. else
  67. {
  68. tree[i].lchild=-1;
  69. }
  70. if(r[0]!='-')
  71. {
  72. tree[i].rchild=r[0]-'0';
  73. tree[r[0]-'0'].flag=1;
  74. }
  75. else
  76. {
  77. tree[i].rchild=-1;
  78. }
  79. }
  80. for(i=0;i<n;i++)
  81. {
  82. if(tree[i].flag==0)
  83. {
  84. k=i;
  85. break;
  86. }
  87. }
  88. //printf("%d\n",k);
  89. levelorder(k);
  90. printf("\n");
  91. inorder(k);
  92. printf("\n");
  93. return 0;
  94. }

发表评论

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

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

相关阅读