您的位置:首页 > 编程语言 > C语言/C++

C++ 二叉树的创建以及遍历

2014-01-06 15:46 369 查看
在笔试面试的过程中,二叉树也是难点之一,考的也是比较多的。我也是被这个问题给难倒过,不能在一个地方摔两次啊!虽然这个东西第一次写出来了,可是如果长时间不看不写不用,还是很容易忘记的。温故而知新,老子还是很厉害的啊,要谨记老子的话了。废话不多说,直接上代码吧!还是一样在VC6.0上调试过的。

#include <stdio.h>
#include <iostream>
#include <string>

using namespace std;

typedef struct BT
{
char data;
struct BT *lch,*rch;
}BT;

void CreatBT(BT *L,string str,int r) //建立二叉树
{
L->data = str[r];
if (str[r*2+1]=='#'||r*2+1>str.size()-1)
{
L->lch = NULL;
}
else
{
L->lch = new BT;
CreatBT(L->lch,str,r*2+1);
}
if (str[r*2+2]=='#'||r*2+2>str.size()-1)
{
L->rch = NULL;
}
else
{
L->rch = new BT;
CreatBT(L->rch,str,r*2+2);
}
}

void preorder(BT *root)//先序遍历二叉树
{
cout<<root->data<<" ";
if (root->lch != NULL)
{
preorder(root->lch);
}
if (root->rch !=NULL)
{
preorder(root->rch);
}
}

void inorder(BT *root)//中序遍历二叉树
{
if (root->lch !=NULL)
{
inorder(root->lch);
cout<<root->data<<" ";//输出带有左右子树的根节点
if (root->rch != NULL)
{
inorder(root->rch);
}
}
else
{
cout<<root->data<<" ";//输出无左右子树的根节点
}
}

void postorder(BT *root)//后序遍历二叉树
{
if (root->lch !=NULL)
{
postorder(root->lch);
}
if (root->rch != NULL)
{
postorder(root->rch);
}
cout<<root->data<<" ";
}

int main()
{
BT *L = new BT;
string str;
cin>>str;
CreatBT(L,str,0);
cout<<"先序遍历二叉树:";
preorder(L);
cout<<endl;
cout<<"中序遍历二叉树:";
inorder(L);
cout<<endl;
cout<<"后序遍历二叉树:";
postorder(L);
cout<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: