算法杂谈--关于二叉树

来源:互联网 发布:企业域名实名认证 编辑:程序博客网 时间:2024/05/17 04:48

本例中涉及二叉树的创建、先序遍历、广度优先遍历、深度


二叉树的广度优先遍历

思路;用一个链表保存每一层的节点,然后通过递归得到解,详见gdyx函数


#include <stdio.h>#include <stdlib.h>#include <assert.h>//二叉树的结构体typedef struct btree{int data;struct btree *left;struct btree *right;}btree;//创建一颗二叉树void create(btree *root){if(root==NULL)return;//a[0]记录左孩子的值,a[1]记录右孩子的值,如果值为负数,则表示该子节点为NULLint a[2];btree *temp;printf("construct %d is child:",root->data);scanf("%d",&a[0]);scanf("%d",&a[1]);if(a[0]<0)root->left=NULL;else{temp=(btree*)malloc(sizeof(btree));temp->data=a[0];root->left=temp;}if(a[1]<0)root->right=NULL;else{temp=(btree*)malloc(sizeof(btree));temp->data=a[1];root->right=temp;}//递归构造二叉树create(root->left);create(root->right);}//先序遍历,其实也是深度优先遍历的结果void preorder(btree *root){if(!root)return;//有左右子节点if(root->left&&root->right){printf("%d",root->data);preorder(root->left);preorder(root->right);}//左右子节点只有其一else if(root->left&&!root->right){printf("%d",root->data);preorder(root->left);}else if(!root->left&&root->right){printf("%d",root->data);preorder(root->right);}//无任何的子节点else{printf("%d",root->data);}}//计算二叉树的深度int depth(btree *root){if(!root)return 0;else{int lv=0,rv=0;lv=depth(root->left);rv=depth(root->right);return (lv>rv?lv:rv)+1;}}//用于广度优先遍历的单链表typedef struct btlist{btree *node;struct btlist *next;}btlist;//在单链表的末尾插入节点void insertail(btlist **l,btlist *p){assert(p!=NULL);if(*l==NULL)*l=p;else{btlist *temp=*l;while(temp->next)temp=temp->next;temp->next=p;p->next=NULL;}}//回收单链表所占的存储空间void freelist(btlist *l){if(l==NULL)return;btlist *temp;while(l){temp=l;l=l->next;free(temp);temp=NULL;}}//广度优先遍历二叉树void gdyx(btlist *list){btlist *nd=list;if(nd==NULL)return;//下一层的节点链btlist *l=NULL;btlist *p;//只要该层的节点链还有新的节点,则依次取出while(nd){printf("%d",nd->node->data);//如果该节点有左孩子,则将左孩子存入节点链if(nd->node->left!=NULL){p=(btlist*)malloc(sizeof(btlist));p->node=nd->node->left;insertail(&l,p);}//如果该节点有右孩子,则将右孩子存入节点链if(nd->node->right!=NULL){p=(btlist*)malloc(sizeof(btlist));p->node=nd->node->right;insertail(&l,p);}nd=nd->next;}//递归遍历下一层的节点链gdyx(l);//回收内存freelist(l);}int main(){btree *root=(btree*)malloc(sizeof(btree));int data;printf("Input root vaule:");scanf("%d",&data);root->data=data;root->left=NULL;root->right=NULL;create(root);printf("The depth of this tree is %d\n",depth(root));printf("深度优先的结果:");preorder(root);putchar('\n');btlist bl;bl.node=root;bl.next=NULL;printf("广度优先的结果:");gdyx(&bl);putchar('\n');return 0;}


图例:

运行结果:



原创粉丝点击