二叉树遍历
1.题目描述:
编一个程序,读入用户输入的一串先序遍历字符串,根据此字符串建立一个二叉树(以指针方式存储)。 例如如下的先序遍历字符串: ABC##DE#G##F### 其中“#”表示的是空格,空格字符代表空树。建立起此二叉树以后,再对二叉树进行中序遍历,输出遍历结果。
输入描述:
输入包括1行字符串,长度不超过100。
输出描述:
可能有多组测试数据,对于每组数据,
输出将输入字符串建立二叉树后中序遍历的序列,每个字符后面都有一个空格。
每个输出结果占一行。
示例1
输入
复制
abc##de#g##f###
输出
复制
c b e g d f a
2.基本思路
对于该题已知前序遍历的结果,需要输出其中序遍历的结果。因此首先我们需要根据二叉树的前序遍历的结果来构造二叉树,由于该问题在遍历的结果中同时输出了空节点的值,因此其只需要该序列便可以唯一的确定二叉树的结构。基本思路就是采用先序遍历的步骤来构造二叉树。然后再对构建后的二叉树进行中序遍历(此时无需输出空节点的值)
3.代码实现
#include <iostream>
#include <string.h>
#define N 101
using namespace std;
struct Node{
Node* lchild;
Node* rchild;
char c;
}Tree[N];
int loc;//Tree数组已分配的结点个数
char str[N];
int cnt=0;
Node* create(){
Tree[loc].lchild=Tree[loc].rchild=NULL;
return &Tree[loc++];
}
Node* build(){
Node* root = create();
if(str[cnt]=='#'){
root->c = ' ';
}
else{
root->c = str[cnt];
}
cnt++;
if(root->c!=' '){//如果左子树不为空,递归构造左子树
root->lchild = build();
root->rchild = build();
}
return root;
}
void inOrder(Node* T){
if(T->lchild->c!=' ')
inOrder(T->lchild);
printf("%c ",T->c);
if(T->rchild->c!=' ')
inOrder(T->rchild);
}
int main()
{
while(gets(str)){
loc=0;
Node* T = build();
inOrder(T);
printf("\n");
}
return 0;
}
/*
abc##de#g##f###
c b e g d f a
*/