标签:oid 流程 logs ade push stat 中序遍历 alt tac
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
树的中序遍历的算法流程如下:
根据树的中序遍历的过程是可以还原出一棵树的。思路如下:在处理输入时,用一个变量保存当前根结点,每当有POP操作时,更新为弹出的元素。每次有PUSH操作时,如果上一次也是PUSH,说明是在遍历左结点,更新TOP的左结点,否则,说明在遍历右结点,更新当前根结点的右结点。
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <queue>
#include <stack>
#include <string>
using namespace std;
struct node
{
int left;
int right;
};
node tree[30] = {0};
int N;
void PostOrderTraversal(int pos)
{
static int outnum = 0;
if (pos)
{
PostOrderTraversal(tree[pos].left);
PostOrderTraversal(tree[pos].right);
if (outnum == 0)
cout << pos;
else
cout << ' ' << pos;
outnum++;
}
}
int main()
{
stack<int> S;
string p,p_last;
int num;
int header,ht=0,flag=1;
int node_last;
cin >> N;
cin.get();
for(int i=0;i<2*N;i++)
{
cin >> p;
if (p == "Push")
{
cin >> num;
if(num==N)
flag = 0;
if (ht!=0)
{
if (p_last=="Push") //上一次也是push说明在遍历左子树,否则是从左子树退回根结点
tree[S.top()].left = num;
else
tree[node_last].right = num;
S.push(num);
}
else
{
header = num;
S.push(num);
}
}
else if (p == "Pop")
{
node_last = S.top();
S.pop();
//cout << node_last<<endl;
}
cin.get();
p_last = p; //记录本次操作
ht++;
}
PostOrderTraversal(header);
return 0;
}
标签:oid 流程 logs ade push stat 中序遍历 alt tac
原文地址:http://www.cnblogs.com/messier/p/8000472.html