1086. Tree Traversals Again (25)

来源:互联网 发布:研究生课程表软件 编辑:程序博客网 时间:2024/05/21 07:01

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:
6Push 1Push 2Push 3PopPopPush 4PopPopPush 5Push 6PopPop
Sample Output:
3 4 2 6 5 1
--------------------------华丽的分割线--------------------------
分析:用一个结构数组来存树的信息,多了个域来保存父节点信息。根据一开始的Push和Pop操作构造好树,之后再后序遍历输出。
代码:
#include<cstdio>#include<cstdlib>#include<cstring>#define Maxn 31typedef struct{int parent;int leftchild;int rightchild;}Node;Node tree[Maxn];bool visited[Maxn];int N;int visitednum;int findnovisitedparent(int thisparent);void postorder(int rootnode);int main(void){scanf("%d\n",&N);int i;int total = 2*N;char operation[5];int index;int thisparent = 0;bool root = false;int rootnode = 0;for(i=0;i<total;++i){scanf("%s",operation);if(strstr(operation,"Push") != NULL){scanf("%d",&index);if(!root){rootnode = index;tree[index].parent = -1;tree[index].leftchild = -1;tree[index].rightchild = -1;thisparent = index;root = true;continue;}else{tree[index].parent = thisparent;tree[index].leftchild = -1;tree[index].rightchild = -1;if(tree[thisparent].leftchild == -1){tree[thisparent].leftchild = index;}else{tree[thisparent].rightchild = index;}thisparent = index;}}if(strstr(operation,"Pop") != NULL){if(!visited[thisparent]){visited[thisparent] = true;}else{thisparent = findnovisitedparent(thisparent);visited[thisparent] = true;}}}postorder(rootnode);system("pause");return 0;}int findnovisitedparent(int thisparent){int temp = tree[thisparent].parent;if(!visited[temp])return temp;elsereturn findnovisitedparent(temp);}void postorder(int rootnode){if(tree[rootnode].leftchild != -1)postorder(tree[rootnode].leftchild);if(tree[rootnode].rightchild != -1)postorder(tree[rootnode].rightchild);printf("%d",rootnode);++visitednum;if(visitednum != N)printf(" ");}


0 0
原创粉丝点击