二叉树的建立和遍历
2014-03-28 13:24
423 查看
二叉树是一种重要的数据结构,今天花了点时间把二叉树的递归建立和不同的遍历方法用C++实现了
下面是具体的代码
下面是具体的代码
//测试用例abc##de#g##f### #include<iostream> #include<queue> using namespace std; typedef struct node{ char data; struct node* lchild; struct node* rchild; }bitree; bitree *createTree(bitree* root){ char c; cin>>c; if(c=='#') root = NULL; else{ root = new bitree; root->data = c; root->lchild = createTree(root->lchild); root->rchild = createTree(root->rchild); } return root; } void inOrder(bitree* root){//中遍历序 if(!root) return; inOrder(root->lchild); cout<<root->data; inOrder(root->rchild); } void preOrder(bitree* root){//先序遍历 if(!root) return; cout<<root->data; preOrder(root->lchild); preOrder(root->rchild); } void postOrder(bitree* root ){//后序遍历 if(!root) return; postOrder(root->lchild); postOrder(root->rchild); cout<<root->data; } void levelOrder(bitree* root){//层次遍历 queue<bitree*> bitQueue; bitQueue.push(root); while(!bitQueue.empty()){ cout<<bitQueue.front()->data<<" "; if(bitQueue.front()->lchild) bitQueue.push(bitQueue.front()->lchild); if(bitQueue.front()->rchild) bitQueue.push(bitQueue.front()->rchild); bitQueue.pop(); } } int main(){ bitree* root; root = createTree(root); preOrder(root);cout<<endl; inOrder(root);cout<<endl; postOrder(root);cout<<endl; levelOrder(root);cout<<endl; return 0; }
相关文章推荐
- Tree 二叉树的建立 和遍历
- 建立平衡二叉树+层次遍历
- 二叉树的建立与遍历
- 二叉树 的建立及遍历 过程
- 二叉树的建立(非递归建立与定义建立)与基本操作(广度和深度遍历,求叶子树高)实现
- 二叉树的建立和遍历算法 - 数据结构和算法47
- 大话数据结构——二叉树的建立于遍历
- 数据结构实验之二叉树的建立与遍历
- UVa 122 Trees on the level 建立二叉树BFS层序遍历
- 二叉树的建立以及六种递归非递归遍历
- 二叉树基本数学知识,建立及三种递归遍历
- 二叉树的遍历建立
- HDU 5444.Elven Postman【2015 ACM/ICPC Asia Regional Changchun Online】【二叉树建立与遍历】9月14
- 二叉树建立以及先序、中序、后序、层次遍历(JAVA 实现)
- SDUT 2136、2137 二叉树的建立与各种遍历
- 二叉树建立、遍历(前序,中序,后序),求叶节点个数,求节点个数
- 数据结构 二叉树的建立与遍历
- (10.28)递归建立一个二叉树,交换左右节点,并遍历
- 二叉树的建立删除及三种遍历实现
- (十)先序序列建立和遍历二叉树