C语言二叉树建立、遍历、交换子树代码

上传人:宝路 文档编号:23258306 上传时间:2017-11-30 格式:DOC 页数:5 大小:33.01KB
返回 下载 相关 举报
C语言二叉树建立、遍历、交换子树代码_第1页
第1页 / 共5页
C语言二叉树建立、遍历、交换子树代码_第2页
第2页 / 共5页
C语言二叉树建立、遍历、交换子树代码_第3页
第3页 / 共5页
C语言二叉树建立、遍历、交换子树代码_第4页
第4页 / 共5页
C语言二叉树建立、遍历、交换子树代码_第5页
第5页 / 共5页
亲,该文档总共5页,全部预览完了,如果喜欢就下载吧!
资源描述

《C语言二叉树建立、遍历、交换子树代码》由会员分享,可在线阅读,更多相关《C语言二叉树建立、遍历、交换子树代码(5页珍藏版)》请在金锄头文库上搜索。

1、C 语言二叉树建立, 遍历(递归与非递归), 交换子树(代码)/C 版二叉树建立,遍历(递归与非递归),交换子树#include#include#includeusing namespace std;/建树typedef struct Nodeint data;Node *lchild,*rchild;btree;btree *create(int a,int n,int i)btree *t;if(in)t=NULL;elset=new btree;t-data=ai-1;t-lchild=create(a,n,2*i);t-rchild=create(a,n,2*i+1);return t

2、;/前序遍历(递归)void preorder(btree *p)if(p!=NULL)coutdatalchild);preorder(p-rchild);/前序遍历(非递归)void preorder1(btree *p)stack s;while(!s.empty()|p!=NULL) while(p!=NULL)coutdatalchild;p=s.top();s.pop();p=p-rchild;/中序遍历(递归)void inorder(btree *p)if(p!=NULL)inorder(p-lchild);coutdatarchild);/中序遍历(非递归)void inor

3、der1(btree *p)stack s;while(!s.empty()|p!=NULL)while(p!=NULL)s.push(p);p=p-lchild;p=s.top();coutdatarchild;/后序遍历(递归)void postorder(btree *p)if(p!=NULL)postorder(p-lchild);postorder(p-rchild);coutdata s;node post;while(!s.empty()|p!=NULL)while(p!=NULL)post.t=p;post.flag=0;s.push(post);p=p-lchild;if(!

4、s.empty()post=s.top();s.pop();if(post.flag=0)post.flag=1;s.push(post);p=(post.t)-rchild;elsecoutdata q;btree *t;if(p!=NULL)q.push(p);while(!q.empty()t=q.front();coutdatalchild!=NULL)q.push(t-lchild);if(t-rchild!=NULL)q.push(t-rchild);/对二叉树 t 中所有结点的左右子树进行交换void exchange(btree *p)btree *t;if(p!=NULL)t

5、=p-lchild;p-lchild=p-rchild;p-rchild=t;exchange(p-lchild);exchange(p-rchild);void main()btree *root;int a5=1,2,3,4,5;root=create(a,5,1);coutpreorder:endl;preorder(root);coutpreorder1:endl; preorder1(root);coutinorder:endl;inorder(root);coutinorder1:endl;inorder1(root);coutpostorder:endl;postorder(root);coutpostorder1:endl;postorder1(root);coutlayerorder:endl;layerorder(root);exchange(root);coutafter exchange(layerorder):endl;layerorder(root);

展开阅读全文
相关资源
相关搜索

当前位置:首页 > 办公文档 > 其它办公文档

电脑版 |金锄头文库版权所有
经营许可证:蜀ICP备13022795号 | 川公网安备 51140202000112号