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.
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:
6
Push 1
Push 2
Push 3
Pop
Pop
Push 4
Pop
Pop
Push 5
Push 6
Pop
Pop
Sample Output:
3 4 2 6 5 1
题目的意思就是输入一颗二叉树的先序遍历和中西医遍历,让你输出后序遍历
Push操作的是先序遍历 Pop操作的是中序遍历
我们可以用一个堆栈来模拟输入的Push和Pop操作。 其中用到了c++中的strcmp函数
注意:strcmp函数只对char类型进行比较 所以,用 string str;cin>>str; 来接受输入的Push或者Pop在strcmp上是运行不过去的
就可以用char ch[5]; cin>>ch; 来进行字符串的输入
以下是代码
#include <bits/stdc++.h> using namespace std; struct node { int data; // int layer; ///存放层数 node * left; node * right; }; node * root = new node; int n; int pre[100]; int in[100]; /// 返回的是root根节点的地址 node *CreatTree(int PL,int PR,int IL,int IR) ///由先序遍历和中序遍历创建一颗二叉树 方法用的是根据先序的左右子树 ///范围和中序的左右子树的范围 { if(PL>PR) ///说明孩子树已经不存在了 return NULL; int k=0; node* root=new node; root->data=pre[PL]; for(k=IL; k<=IR; k++) { if(pre[PL] == in[k]) ///说明找到了根节点 break; } int numLeft=k-IL; root->left=CreatTree(PL+1,PL+numLeft,IL,k-1); ///返回的是左子树的地址 root->right=CreatTree(PL+numLeft+1,PR,k+1,IR); ///返回的是右子树的地址 return root; } int cnt=0; ///cnt用来进行控制空格的输出 void postorder(node * root) ///后序遍历 { if(root==NULL) return ; postorder(root->left); postorder(root->right); cout<<root->data; if(cnt<n) cout<<" "; cnt++; } void f() ///题目上要求的输入 { stack<int> st; ///用堆栈来对题目中的Push和Pop进行模拟 cin>>n; int pk=0; int ik=0; for(int i=0; i<2*n; i++) { char str[5]; cin>>str; if(strcmp(str,"Push")==0) { int num; cin>>num; st.push(num); pre[pk++]=num; } else { in[ik++]=st.top(); st.pop(); } } } int main() { f(); root=CreatTree(0,n-1,0,n-1); postorder(root); return 0; }