/***********************/ /****Author:Guo Junling*/ /********Date:2004.11.2*/ /*Description:Create a tree and travelsal it in three different ways*/ /***********************/ #i nclude <stdio.h> #i nclude <stdlib.h> #i nclude <conio.h> #define MAX 100 /*define a tree*/ typedef struct tnode { int data; struct tnode *lchild,*rchild; }TNODE; void create(); TNODE *insert(int ); /*插入结点函数*/ void inorder(TNODE *); /*中序遍历函数*/ void preorder(TNODE *); /*先序遍历函数*/ void postorder(TNODE *); /*后序遍历函数*/ /*define a global variable*/ TNODE *root=NULL; /*main function*/ void main() { create(); printf("----------INORDER------------/n"); inorder(root); printf("/n-----------------------------/n/n/n"); printf("----------PREORDER-----------/n"); preorder(root); printf("/n-----------------------------/n/n/n"); printf("----------POSTORDER----------/n"); postorder(root); printf("/n-----------------------------/n/n/n"); getch(); } /*function:travelsal of the tree in inorder*/ void inorder(TNODE *ptr) { if(ptr!=NULL) { inorder(ptr->lchild); printf("%d ",ptr->data); inorder(ptr->rchild); } } /*function:travelsal of the tree in preorder*/ void preorder(TNODE *ptr) { if(ptr!=NULL) { printf("%d ",ptr->data); preorder(ptr->lchild); preorder(ptr->rchild); } } /*function:travelsal of the tree in postorder*/ void postorder(TNODE *ptr) { if(ptr!=NULL) { postorder(ptr->lchild); postorder(ptr->rchild); printf("%d ",ptr->data); } } /*Function:Create a linked list*/ void create() { int n,i; int k[MAX]; printf("please input the node number of your tree:/n"); scanf("%d",&n); for(i=0;i<n;i++) { scanf("%d",&k[i]);/*输入节点信息,并保存到一个数组中去*/ insert(k[i]); /*将节点插入到树中去*/ } } /*function:Insert a node into a tree*/ TNODE *insert(int m) { TNODE *p1,*p2; if(root==NULL) { root=(TNODE *)malloc(sizeof(TNODE)); root->data=m; /*树根*/ root->lchild=root->rchild=NULL; } else { p1=root; while(m!=p1->data) { if((m<p1->data)&&(p1->lchild!=NULL)) p1=p1->lchild; else if(m>(p1->data)&&(p1->rchild!=NULL)) p1=p1->rchild; else if(m<(p1->data)&&(p1->lchild==NULL)) { p2=(TNODE *)malloc(sizeof(TNODE)); p2->data=m; p2->lchild=p2->rchild=NULL; p1->lchild=p2; } else if((m>p1->data)&&(p1->rchild==NULL)) { p2=(TNODE *)malloc(sizeof(TNODE)); p2->data=m; p2->lchild=p2->rchild=NULL; p1->rchild=p2; } } } return(root); } |
树及其三种遍历
最新推荐文章于 2023-03-31 15:15:05 发布