二叉树的基本操作
来源:互联网 发布:python math.ceil 编辑:程序博客网 时间:2024/05/17 07:31
本文就二叉树的基本操作进行总结
包括二叉树的建立、递归遍历、非递归遍历、层序遍历等
二叉树的结构体如下
typedef struct _node{char data;struct _node* lchild;struct _node* rchild;}node;
1.二叉树的建立
void create(node*& tree){char data;scanf("%c",&data);if ('#'==data){tree=NULL;return;}tree=(node*)malloc(sizeof(node));tree->data=data;printf("输入%c的左节点:",data);create(tree->lchild);printf("输入%c的右节点:",data);create(tree->rchild);}
2.递归遍历
void preOrder(node* tree) //先序递归遍历{if(tree){printf("%c",tree->data);preOrder(tree->lchild);preOrder(tree->rchild);}}void inOrder(node* tree) //中序递归遍历{if(tree){inOrder(tree->lchild);printf("%c",tree->data);inOrder(tree->rchild);}}void postOrder(node* tree) //后序递归遍历{if(tree){postOrder(tree->lchild);postOrder(tree->rchild);printf("%c",tree->data);}}
3.非递归遍历
非递归遍历利用队列实现
void preOrder1(node* tree) //先序非递归遍历{deque<node*> q;node* t=tree;while (t!=NULL||!q.empty()) {while (t!=NULL) {printf("%c",t->data);q.push_back(t);t=t->lchild;}t=q.back();q.pop_back();t=t->rchild;}}void inOrder1(node* tree) //中序非递归遍历{deque<node*> q;node* t=tree;while (t!=NULL||!q.empty()) {while (t!=NULL) {q.push_back(t);t=t->lchild;}t=q.back();q.pop_back();printf("%c",t->data);t=t->rchild;}}void postOrder1(node* tree) //后序非递归遍历{deque<node*> q;node* t=tree;node* prerchild=NULL;while (t!=NULL||!q.empty()) {while (t!=NULL) {q.push_back(t);t=t->lchild;}t=q.back();if (t->rchild==NULL||t->rchild==prerchild) {q.pop_back();printf("%c",t->data);prerchild=t;t=NULL;}else{t=t->rchild;}}}
4.层序遍历
层序遍历也是借助队列实现的
void levelOrder(node* tree){deque <node*> q;if (!tree) return;node* t=tree;q.push_back(t);while (!q.empty()) {t=q.front();q.pop_front();printf("%c",t->data);if (t->lchild) q.push_back(t->lchild);if (t->rchild) q.push_back(t->rchild);}}
层序遍历有时候,还需要将不同层之间分层输出,实现如下
void levelOrder1(node* tree){deque<node*> q;if (NULL==tree) return; node* t=tree;q.push_back(t);int levelNum=1;while(!q.empty()){levelNum=q.size();for (int i=0;i<levelNum;i++) {t=q.front();q.pop_front();printf("%c",t->data);if (t->lchild!=NULL) {q.push_back(t->lchild);}if (t->rchild!=NULL) {q.push_back(t->rchild);}}printf("\n");}}
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 架构师必读书(不断更新中)
- PV原语小结
- swing下拉框显示表格内容解决方案
- 添加源
- activity 使用runOnUiThread更新 ui
- 二叉树的基本操作
- C# 删除html标签,只保留文字
- 单片机IO端口工作原理
- Net Micro Framework 快速入门
- 深入浅出“输入输出”
- linux 多线程小例子
- 单片机IO口结构及上拉电阻
- Intent和Intent-filter
- 线段树基本应用——区间最值查询