二叉树的创建,遍历,查找算法及其程序实现(傻瓜版)

来源:互联网 发布:中控考勤机上传数据 编辑:程序博客网 时间:2024/05/07 20:21

前一个月学习了一下二叉树,现在和大家分享一下。(高手勿看)

二叉树常被用于实现二叉查找树和二叉堆。值得注意的是,二叉树不是树的特殊情形。在图论中,二叉树是一个连通的无环图,并且每一个顶点的度不大于3。有根二叉树还要满足根结点的度不大于2。有了根结点后,每个顶点定义了唯一的根结点,和最多2个子结点。然而,没有足够的信息来区分左结点和右结点。

请看下面的程序:

//二叉树创建->前序中序后序遍历->查找#include<stdio.h> #include<stdlib.h> typedef struct bitnode { char data; struct bitnode *lchild,*rchild; }bitnode,*bitree;//二叉树节点类型和节点指针类型 bitree create()//先序创建 { bitree root=NULL; char c; scanf("%c",&c); fflush(stdin); if(c=='#')return NULL; else { root=(bitnode*)malloc(sizeof(bitnode)); root->data=c; root->lchild=create(); root->rchild=create(); } return root; } void preorder(bitree root)//先序遍历 { if(!root)return; else { putchar(root->data); //一个个输出根preorder(root->lchild); preorder(root->rchild); } } void inorder(bitree root)//中序遍历 { if(!root)return; else { inorder(root->lchild); putchar(root->data); inorder(root->rchild); } } void postorder(bitree root)//后序遍历 { if(!root)return; else { postorder(root->lchild); postorder(root->rchild); putchar(root->data); } } bitnode *Search(bitnode *head,char key){if(head!=NULL){if(head->data == key){printf("............找到............\n");printf("\n对应的数据域=%d,对应的地址=%d\n\n\n",head->data,head);return(head); /*已经找到*/}Search(head->lchild,key); Search(head->rchild,key); }return(NULL);}void main() {   char m;bitree root=NULL; printf("输入先序序列:(每次输入一个字符回车)\n");root=create(); printf("输入查找的结点:\n");m=getchar();    Search(root,m);printf("前序遍历:\n"); preorder(root); printf("\n"); printf("中序遍历:\n"); inorder(root); printf("\n"); printf("后序遍历:\n"); postorder(root); printf("\n"); } /*输入序列为前序序列,#代表空 例如二叉树为 --------a -------/-\ ------b---c -----/-\ ----d---e 输入abd##e##c##*/ 

这个程序实现二叉树的创建,遍历,查找还是比较简单的,很容易看懂,因为它没有用到栈的知识,而是类似于递归一样的解析,具体就不做详细的论述了。

原创粉丝点击