您的位置:首页 > 理论基础 > 数据结构算法

二叉树的建立和遍历

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息