二叉树及按层遍历的算法实现
2011-09-02 20:25
411 查看
/****************************** // 建立二叉树 // 及按层遍历的算法实现 ******************************/ #include<stdio.h> #include<stdlib.h> #include<string.h> #define size 256 typedef char datatype; typedef struct node { datatype data; struct node *lchild; struct node *rchild; }*root,treenode; void init(root *t) { (*t) = NULL; } void input(char *pre_str, char *in_str ) { printf("please input the pre_order string:\n"); gets(pre_str); printf("please input the in_order string:\n"); gets(in_str); if(strlen(pre_str) != strlen(in_str)){ puts("different string !!!"); } } void build(char *pre_str,char *in_str,int len,root *t) { if(pre_str == NULL || in_str == NULL) return ; (*t) = (root)malloc(sizeof(treenode)); (*t)->data=*pre_str; (*t)->lchild=NULL; (*t)->rchild=NULL; if(len == 1) return ; char *first=in_str; char *move=in_str; int tmp_len=0; while((*pre_str) != *move){ if(pre_str == NULL || move == NULL) return ; tmp_len++; if(tmp_len>len) break; move++; } int l_len,r_len; l_len = (int)(move-first); r_len = (len-l_len-1); if(l_len > 0) build(pre_str+1,in_str,l_len,&((*t)->lchild)); if(r_len > 0) build(pre_str+1+l_len,in_str+1+l_len,r_len,&((*t)->rchild)); } void travel_pre(root t) { if(t == NULL) return ; printf("%c ",t->data); travel_pre(t->lchild); travel_pre(t->rchild); } void travel_in(root t) { if(t == NULL) return ; travel_in(t->lchild); printf("%c ",t->data); travel_in(t->rchild); } void travel_post(root t) { if(t == NULL) return ; travel_post(t->lchild); travel_post(t->rchild); printf("%c ",t->data); } void travel_level(root t) { root quen[size]; int front=-1; int rear=-1; rear++; quen[rear] = t; while(front != rear){ root tmp; front=(front+1) % size; tmp=quen[front]; printf("%c ",tmp->data); if(tmp->lchild != NULL){ rear = (rear+1)%size; quen[rear]=tmp->lchild; } if(tmp->rchild != NULL){ rear = (rear+1)%size; quen[rear]=tmp->rchild; } } } int main(void) { root t; init(&t); int len; char pre_str[size]; char in_str[size]; input(pre_str,in_str); len = strlen(pre_str); build(pre_str,in_str,len,&t); printf("the pre_order is: \n"); travel_pre(t); printf("\n"); printf("the in_order is:\n"); travel_in(t); printf("\n"); printf("the post_order is:\n"); travel_post(t); printf("\n"); printf("the level_order is:\n"); travel_level(t); printf("\n"); return 0; }
相关文章推荐
- 【LeetCode-面试算法经典-Java实现】【107-Binary Tree Level Order Traversal II(二叉树层序遍历II)】
- java实现二叉树的三种遍历算法(递归)
- java实现二叉树的三种遍历算法(递归)
- 二叉树的遍历算法Java实现
- 数据结构编程笔记十四:第六章 树和二叉树 二叉树基本操作及四种遍历算法的实现
- 二叉树的各种遍历算法的递归和非递归实现
- 【LeetCode-面试算法经典-Java实现】【107-Binary Tree Level Order Traversal II(二叉树层序遍历II)】
- 实现平衡二叉排序树的各种算法(包括二叉树的递归遍历、非递归遍历)
- 经典算法之非递归算法实现二叉树前、中、后序遍历
- Java实现二叉树,以及先序、中序、后序遍历算法的实现
- 算法与数据结构基础4:C++二叉树实现及遍历方法大全
- 【面试算法系列】已知二叉树的前序和中序遍历重建二叉树 - C语言实现
- 二叉树先序、中序、后序遍历算法的实现
- 算法:二叉树的先(根)序遍历、中(根)序遍历、后(根)序遍历(递归及压栈出栈实现的非递归方式)的java代码实现
- 实现二叉树各种遍历算法
- 实现由双亲节点存储的树转化为二叉树的遍历算法实现
- 二叉树三种遍历算法的递归和非递归实现(C++)
- 二叉树的遍历算法实现、以及所有简单操作
- 二叉树的基本操作(含遍历算法非递归实现全收录)
- 二叉树的构建和三种遍历算法 (递归实现)