2022.4.6

洛谷p1305

看了题解后知道,想输出前序遍历就只需要先设string a用于保存根节点及其左右节点,之后再依次输入其他的,

在a中找到其根节点的位置后插入进去即可。

由于刚开始学,我并不会写这种题,看了这个题解后我发现这样的输入也可以输出后序遍历。

改写的关键在于,由于前序遍历为根-左-右,后序遍历为左-右-根,所以可以将输入后的左右节点互换,

使输入的字符串变为根-右-左的形式,然后继续用这种方法插入。再倒序输出即可。

emmmm中序输出还没想//等想到了再改=w=

/* 这是通过给出各个节点及其左右节点而写出前序遍历的代码
#include<string>
#include<iostream>
#include<algorithm>
using namespace std;
struct node
{
int l;
int r;
};
node a[30];
int n;
int main()
{
std::ios::sync_with_stdio(false);
cin>>n;
string a;
cin>>a;
for(int i=1;i<n;i++)
{
string s;
cin>>s;
int x=a.find(s[0]);
s.erase(s.begin());
a.insert(x+1,s);
}
for(int i=0;i<a.size();i++)
{
if(a[i]!='*')
cout<<a[i];
}
cout<<"\n";
return 0;
}
*/

posted @ 2022-04-06 16:19  noname5588  阅读(25)  评论(0)    收藏  举报