您的位置:首页 > 理论基础 > 数据结构算法

数据结构实验之二叉树二:遍历二叉树

2017-10-31 09:36 190 查看


题目中给的是一个先序遍历的序列,所以建立二叉树的过程就是根据先序遍历的序列来建立,然后依次输出中序遍历和后序遍历的序列即可;

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct node{ //开始此处没有加typedef,就没有定义树这种类型,所以会出现variable or field‘createTree’ declared void这种错误
char data;
struct node *lchild, *rchild;
}*bitTree;
int cnt = 0;
char str[100];
void createTree(bitTree &root, char str[]){
char ch = str[cnt++];
if(ch == ',')
root = NULL;
else {
root = new node;
root->data = ch;
createTree(root->lchild, str);
createTree(root->rchild, str);
}
}
void zhongxu(bitTree root){
if(root){
zhongxu(root->lchild);
printf("%c", root->data);
zhongxu(root->rchild);
}
}
void houxu(bitTree root){
if(root){
houxu(root->lchild);
houxu(root->rchild);
printf("%c", root->data);
}
}

int main(){
while(~scanf("%s", str)){
cnt = 0;
bitTree root;
createTree(root, str);
zhongxu(root);
printf("\n");
houxu(root);
printf("\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  二叉树