- 有标记叶节点,可以用线性数组来储存。
- 用各种变量表示状态。
filed→结点数量。注意上一层的叶节点会影响到下面全部层,所以不需要清零。
old→本次开始遍历的结点
node→这一层的非空结点。old+node构成了每一次遍历的下标。
height→第几层,根据这个判断高度和非空结点数量。 - 只要能保存这棵树,再分层读取就好了。
- 再次把倒序输出时保存每一层的变量的栈放错了位置导致更新一次就清空一次。
- 注意是先弹出栈顶元素影响数量还是后弹出。
- 看清楚输出哪里有空格,哪里没有。题解的4的后面是有空格的。这意味着可以在输出的时候就直接判断有没有空格。
- 自己电脑测试能不能输出空格就停止输入的方法(头文件#include):
while (cin >> str) {//string遇到空格会停止
tree[i++] = str;
char ch = getchar();//通过getchar()来判断最后输入回车符结束
if (ch == '\n') break;
}
源代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<cmath>
#include<stack>
using namespace std;
string tree[10000];
int main()
{
int i=0;
string str;
while (cin >> str) {//string遇到空格会停止
tree[i++] = str;
char ch = getchar();//通过getchar()来判断最后输入回车符结束
if (ch == '\n') break;
}
int cum = 0;
int height = 0;//偶数层从右边往左边遍历,奇数层反过来
int filed = 0;//储存这一层有多少叶子结点
int old = 0;
stack<string> temp;
while (cum < i)
{
int node = pow(2, height) - 2 * filed;
filed *= 2;
while(cum < old + node)
{
if (tree[cum] == "#")
filed++;
if (!(height % 2))
{
if (tree[cum] != "#")
{
cout << tree[cum];
if (cum != old + node - 1)
cout << " ";
else
cout << endl;
}
}
else
{
if (tree[cum] != "#")
temp.push(tree[cum]);
if (cum == old + node - 1)
{
while (!temp.empty())
{
cout << temp.top();
temp.pop();
if (temp.size() >= 1)
cout << ' ';
}
}
}
cum++;
}
old += node;
cout << endl;
height++;
}
system("pause");
}