1086. Tree Traversals Again (25)

﹏ヽ暗。殇╰゛Y 2022-05-29 21:11 201阅读 0赞

An inorder binary tree traversal can be implemented in a non-recursive way with a stack. For example, suppose that when a 6-node binary tree (with the keys numbered from 1 to 6) is traversed, the stack operations are: push(1); push(2); push(3); pop(); pop(); push(4); pop(); pop(); push(5); push(6); pop(); pop(). Then a unique binary tree (shown in Figure 1) can be generated from this sequence of operations. Your task is to give the postorder traversal sequence of this tree.

bs_n9mde9jcnyj.jpg
Figure 1

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive integer N (<=30) which is the total number of nodes in a tree (and hence the nodes are numbered from 1 to N). Then 2N lines follow, each describes a stack operation in the format: “Push X” where X is the index of the node being pushed onto the stack; or “Pop” meaning to pop one node from the stack.

Output Specification:

For each test case, print the postorder traversal sequence of the corresponding tree in one line. A solution is guaranteed to exist. All the numbers must be separated by exactly one space, and there must be no extra space at the end of the line.

Sample Input:

  1. 6
  2. Push 1
  3. Push 2
  4. Push 3
  5. Pop
  6. Pop
  7. Push 4
  8. Pop
  9. Pop
  10. Push 5
  11. Push 6
  12. Pop
  13. Pop

Sample Output:

  1. 3 4 2 6 5 1

题目大意:

代码:

  1. #include<stdio.h>
  2. #include<stack>
  3. using namespace std;
  4. struct node
  5. {
  6. int data;
  7. int lchild,rchild;
  8. }tree[50];
  9. int pre[100],in[100],l1=0,l2=0;
  10. int biuld(int num,int *a,int *b)
  11. {
  12. if(num<=0)
  13. {
  14. return -1;
  15. }
  16. tree[*a].data=*a;
  17. int i;
  18. for(i=0;i<num;i++)
  19. {
  20. if(*(b+i)==*a)
  21. break;
  22. }
  23. tree[*a].lchild=biuld(i,a+1,b);
  24. tree[*a].rchild=biuld(num-i-1,a+i+1,b+i+1);
  25. return *a;
  26. }
  27. int flag=0;
  28. void posttraverl(int root)
  29. {
  30. if(root!=-1)
  31. {
  32. posttraverl(tree[root].lchild);
  33. posttraverl(tree[root].rchild);
  34. if(flag==0)
  35. {
  36. printf("%d",root);
  37. flag=1;
  38. }
  39. else
  40. {
  41. printf(" %d",root);
  42. }
  43. }
  44. }
  45. int main()
  46. {
  47. int i,j,n,m,k,t;
  48. char operation[5];
  49. scanf("%d",&n);
  50. stack<int> s;
  51. for(i=0;i<n*2;i++)
  52. {
  53. scanf("%s",operation);
  54. if(operation[1]=='u')
  55. {
  56. scanf("%d",&m);
  57. s.push(m);
  58. pre[l1++]=m;
  59. }
  60. else
  61. {
  62. in[l2++]=s.top();
  63. s.pop();
  64. }
  65. }
  66. int root=biuld(n,pre,in);
  67. posttraverl(root);
  68. return 0;
  69. }

发表评论

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

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

相关阅读