问题 H: 数据结构(C语言版)算法6.1至算法6.4__二叉树遍历
问题 H: 数据结构(C语言版)算法6.1至算法6.4__二叉树遍历
时间限制: 1 Sec 内存限制: 128 MB
提交: 128 解决: 34
[提交][状态][讨论版]
题目描述
求二叉树的先序、中序及后序遍历序列。结点数<=100。
输入
按先序遍历的顺序建立一个二叉树,为了保证树的唯一性,并在程序中的递归出口是左右子树为空,故输入时,当某结点的左子树或右子树为空值时也要作为先序遍历的有效输入。例如一个树只有3个结点,根结点值为1,其左孩子结点值为2,其右孩子结点值为3,则输入的先序遍历序列依次为1 2 0 0 3 0 0(为空时输入0值)*/
输出
在三行上,依次输出二叉树的先序、中序及后序遍历序列。序列中各数用空格隔开。
样例输入
1 2 0 0 3 0 0
样例输出
1 2 3
2 1 3
2 3 1
提示
一开始狂RE 不知道是不是人品问题 下面是参考了老师给的代码 后 做过的 AC 了
主要 难住我的地方是一开始 不知道如何结束输入 后来知道了就 一组数据 但是仍然不知道如何结束这一组数据的输入
我直接gets 所有的再处理 也不行 用scanf !=EOF 也是RE RE代码见最后面
这个思路很简单 一直建立树接点 如过遇到0 则不建立相应的接点 直接递归建立即可 很简单
#include<stdio.h>#include<string.h>#include<malloc.h>typedef struct haha{ struct haha *l_child; struct haha *r_child; int num;}node;int a[100000];int ans[100000];int n,k;node * make_tree(node *temp){// node *temp;wentichuxianzai zheli// temp=root;caocaocaocao //printf("n=%d\n",n); if(temp==NULL) { if(a[n]!=0) { temp=(node *)malloc(sizeof(node)); temp->l_child=temp->r_child=NULL; temp->num=a[n]; } else return NULL; } ++n; temp->l_child=make_tree(temp->l_child); ++n; temp->r_child=make_tree(temp->r_child); return temp;}void print_pre(node *temp){ ans[k++]=temp->num; if(temp->l_child!=NULL) print_pre(temp->l_child); if(temp->r_child!=NULL) print_pre(temp->r_child);}void print_mid(node *temp){ if(temp->l_child!=NULL) print_pre(temp->l_child); ans[k++]=temp->num; if(temp->r_child!=NULL) print_pre(temp->r_child);}void print_las(node *temp){ if(temp->l_child!=NULL) print_pre(temp->l_child); if(temp->r_child!=NULL) print_pre(temp->r_child); ans[k++]=temp->num;}int main(){ int i,j,d; char s[400000]; node *root; while(gets(s)) { d=strlen(s); j=0; for(i=0;i<d;i++) if('0'<=s[i]&&s[i]<='9') a[j++]=s[i]-'0'; root=NULL; n=0; root=make_tree(root); k=0; print_pre(root); for(i=0;i<k-1;i++) printf("%d ",ans[i]); printf("%d\n",ans[k-1]); k=0; print_mid(root); for(i=0;i<k-1;i++) printf("%d ",ans[i]); printf("%d\n",ans[k-1]); k=0; print_las(root); for(i=0;i<k-1;i++) printf("%d ",ans[i]); printf("%d\n",ans[k-1]); } return 0;}