描述
编一个程序,读入用户输入的一串先序遍历字符串,根据此字符串建立一个二叉树(以指针方式存储)。 例如如下的先序遍历字符串: ABC##DE#G##F### 其中“#”表示的是空格,空格字符代表空树。建立起此二叉树以后,再对二叉树进行中序遍历,输出遍历结果。
输入描述:
输入包括1行字符串,长度不超过100。
输出描述:
可能有多组测试数据,对于每组数据, 输出将输入字符串建立二叉树后中序遍历的序列,每个字符后面都有一个空格。 每个输出结果占一行。
示例1
输入:
abc##de#g##f###
复制输出:
c b e g d f a
版本一:老实把它变成一个树
#include<iostream>
#include<string>
#include<algorithm>
#include<bits/stdc++.h>
using namespace std;
string pre;
int pos=0;
typedef struct BiTree
{
char data;
struct BiTree * lchild,*rchild;
BiTree(char c):data(c),lchild(NULL),rchild(NULL){};
};
BiTree* creat()
{
/**
if(pre[pos]=='#') return NULL;
BiTree *root=new BiTree(pre[pos]);
pos++;
ps:一开始想省事写成这样,结果发现如果为#就不会执行pos++了
**/
char tmp=pre[pos];
pos++;
if(tmp=='#') return NULL;
BiTree *root=new BiTree(tmp);
root->lchild=creat();
root->rchild=creat();
return root;
}
void Traverse(BiTree* root)
{
if(root==NULL) return;
Traverse(root->lchild);
cout<<root->data<<" ";
Traverse(root->rchild);
}
int main()
{
cin>>pre;
BiTree *root=creat();
Traverse(root);
}
版本二:受到一个大佬的启发,直接用线性数组表示一个数,用数字逻辑找到树的左右节点。(就是看成一个满二叉树,然后向里面填节点的值)
#include<iostream>
#include<string>
#include<algorithm>
#include<bits/stdc++.h>
using namespace std;
const int N1=1e8;
string pre;
int pos=0;
char tree[N1];
void creat(int pos_tree)
{
char tmp=pre[pos++];
if(tmp=='#') return;
tree[pos_tree]=tmp;
creat(pos_tree*2);
creat(pos_tree*2+1);
}
void Traverse(int pos_tree)
{
if(tree[pos_tree]==0) return;
Traverse(pos_tree*2);
cout<<tree[pos_tree]<<" ";
Traverse(pos_tree*2+1);
}
int main()
{
cin>>pre;
creat(1);
Traverse(1);
}