二叉树是一种重要的数据结构,今天花了点时间把二叉树的递归建立和不同的遍历方法用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;
}
3546

被折叠的 条评论
为什么被折叠?



