二叉树的建立——广度优先

来源:互联网 发布:java调用docker api 编辑:程序博客网 时间:2024/05/06 00:49


    大家好~~建立这个博客账号纯粹以相互学习为目的;这是我的第一篇文章,希望大家能够喜欢~如果有不同意见,或者更好的算法或数据结构,欢迎和我交流,相互学习,共同进步大笑大笑

    好了,废话不多说,正文开始~~

前言

       大家现在在网上查找“二叉树的建立”时,有很多都是基于递归建立的。虽然使用递归遍历比较简洁,但是个人认为有些不符合广大人们的直观想法,于是,我特意写了一篇广度优先的二叉树建立程序,希望能够对大家有所帮助。

  算法描述  

            算法的流程图如下图所示:
                                                  
                                                     
                                                                                           图1    算法流程图

     算法实现

我用C语言实现了该算法,并用VC++  编译运行,先序遍历验证,结果见后。

#include<stdio.h>#include<stdlib.h>struct tree * creattree(); void Inorder(struct tree * root);struct tree{struct tree *lchildren,*rchildren,*parent;int data;};struct parent{struct tree *root;struct parent *n;};struct parent *p;int main(){struct tree *root;p=NULL;printf("请输入数据(1~n为从左至右的编号):\n");root=creattree();printf("创建成功!\n");printf("该二叉树先序遍历结果如下:");Inorder(root);//中序遍历二叉树来完成数的验证}struct tree *creattree( ){int i=0;//i为节点编号struct tree *root,*t;struct parent *now_parent,*q,*now;char data;//输入的数据now=NULL;now_parent=NULL;scanf("%c",&data);getchar();if (data!='#')//创建根节点{root=(struct tree *)malloc(sizeof(struct tree));root->data=data;root->lchildren=NULL;        root->rchildren=NULL;root->parent=NULL;p=(struct parent *)malloc(sizeof(struct parent));        p->root=root;p->n=NULL;now_parent=p;now=p;i++;}else{printf("创建了空子树!\n");return NULL;}while(now!=NULL){//创建其余节点scanf("%c",&data);getchar();    t=(struct tree *)malloc(sizeof(struct tree));t->lchildren=NULL;t->rchildren=NULL;t->data=data;t->parent=now->root;i++;if (i%2==0){   now->root->lchildren=t;}else{now->root->rchildren=t;}//当节点内容不为“#”时,则该节点可能为父节点if (data!='#'){    q=(struct parent *)malloc(sizeof(struct parent));q->root=t;q->n=NULL;now_parent->n=q;        now_parent=q;}if (i%2==1)now=now->n;}return root;}void Inorder(struct tree * root){if (root==NULL)return ;printf("%c ",root->data);Inorder(root->lchildren);Inorder(root->rchildren);}


图2    运行结果

             

原创粉丝点击