By Jalan
知识工具需求
数学
数据结构和算法
语言
题干
给一个树的中序的栈DFS遍历行为,你得输出一个后序的遍历
输入条件
N<=30个节点1-N
2N行,每行的格式是Push X或者Pop,X是入栈节点的编号.
输出条件
后序末尾无空格
例子
例1
输入
6
Push 1
Push 2
Push 3
Pop
Pop
Push 4
Pop
Pop
Push 5
Push 6
Pop
Pop
输出
3 4 2 6 5 1
题解
第一次
思路
这个栈的操作大概是:
有中&&中未访问:push中continue
有左&&左未访问:push左continue
pop()
有右&&右未访问:push右continue
- 节点只有30个建树很方便,到l数组里
- 观察这些字符串,可以发现,统计push的个数-pop的个数,第一个为0的时候就是pop根结点的时候,这个pop也会把树分成左右两个子树.依据观察的结果编写buildTree函数进行建树.
- 按要求dfs这个树,把postOrder序存在数组result里
- 按要求输出
预期时间复杂度
编写用时
写了2次,第一次想写个在线的,实在是残疾写不出来.
代码
CPP
#include <bits/stdc++.h>
#include <stdio.h>
#include <vector>
using namespace std;
int n;
vector<int> result;
vector<string> l;
typedef struct node
{
int v;
node *l = NULL;
node *r = NULL;
node *f = NULL;
} node;
void buildTree(node *travel, int lIndex, int rIndex)
{
int pushCounter = 0;
int midPopIndex = 0;
int value = 0;
if (l[lIndex].size() == 6)
{
value = l[lIndex][5] - '0';
}
else if (l[lIndex].size() == 7)
{
value = (l[lIndex][5] - '0') * 10 + l[lIndex][6] - '0';
}
travel->v = value;
//找到区分左右子树的那个Pop
for (int i = lIndex; i <= rIndex; i++)
{
if (l[i][1] == 'u')
{
pushCounter++;
}
if (l[i][1] == 'o')
{
pushCounter--;
}
if (pushCounter == 0)
{
midPopIndex = i;
break;
}
}
if (midPopIndex != lIndex + 1) //有左子树
{
node *newNode = new node;
travel->l = newNode;
newNode->f = travel;
buildTree(newNode, lIndex + 1, midPopIndex - 1);
}
if (midPopIndex != rIndex) //有右子树
{
node *newNode = new node;
travel->r = newNode;
newNode->f = travel;
buildTree(newNode, midPopIndex + 1, rIndex);
}
}
void dfs(node *root)
{
if (root->l != NULL)
{
dfs(root->l);
}
if (root->r != NULL)
{
dfs(root->r);
}
result.push_back(root->v);
}
int main(int argc, char const *argv[])
{
//1
scanf("%d", &n);
getchar();
char temp[10];
for (int i = 0; i < n * 2; i++)
{
scanf("%[^\n]", temp);
getchar();
string ins(temp);
l.push_back(ins);
}
//2
node *root = new node;
buildTree(root, 0, n * 2 - 1);
//3
dfs(root);
//4
for (int i = 0; i < n; i++)
{
printf("%d", result[i]);
if (i != n - 1)
{
printf(" ");
}
}
return 0;
}
运行用时
结尾
看在我写了这么多注释的份上可以给我点个赞嘛,求求惹=]砰砰砰,给我加点写下去的油呀@.@
也欢迎关注我的CSDN账号呀,接下来两个月我应该会按这个格式更新所有的PTA甲级题目
**开心code每一天**