7-3 建立与遍历二叉树 (25分)
7-3 建立与遍历二叉树 (25分)
以字符串的形式定义一棵二叉树的先序序列,若字符是‘#’, 表示该二叉树是空树,否则该字符是相应结点的数据元素。读入相应先序序列,建立二叉链式存储结构的二叉树,然后中序遍历该二叉树并输出结点数据。
输入格式:
字符串形式的先序序列(即结点的数据类型为单个字符)
输出格式:
中序遍历结果
输入样例:
在这里给出一组输入。例如:
ABC##DE#G##F###
输出样例:
在这里给出相应的输出。例如:
CBEGDFA
【程序实现】
#include<bits/stdc++.h>
using namespace std;
struct tree{
char data;
struct tree *left;
struct tree *right;
};
char ch[10005];
int i = 0;
struct tree *creat(){
char op = ch[i++];
if(op == '#') return NULL;
struct tree *root = new struct tree;
root->data = op;
root->left = creat();
root->right = creat();
return root;
}
void InorderTraversal(struct tree *root){
if (root != NULL) {
InorderTraversal( root->left );
printf("%c",root->data);
InorderTraversal( root->right );
}
}
int main(){
scanf("%s",ch);
struct tree *root = creat();
InorderTraversal(root);
return 0;
}

浙公网安备 33010602011771号