歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C++實現數據結構的二叉樹及其遍歷二叉樹

C++實現數據結構的二叉樹及其遍歷二叉樹

日期:2017/3/1 10:07:08   编辑:Linux編程

二叉樹的初始化,刪除,遍歷

注意:看是否滿足條件,則必須是在調試的對話框的右下側觀察數據是否滿足是一個樹及其它的左孩子和右孩子

//二叉樹鏈式存儲的實現
#include<iostream>
#include<cstring>
using namespace std;

struct ECS_data //先定義好一個數據的結構
{
char data;
ECS_data *l;
ECS_data *r;
};

class ECS
{
private:
//int level; //樹高
int n; //表示有多少個節點數
int n1; //表示的是數組的總長度值,(包括#),因為後面要進行刪除判斷
ECS_data *temp[1000];
public:
ECS_data *root;
ECS() //初始化
{
ECS_data *p;
char t[1000];int i;
int front=0,rear=1; //front表示有多少個節點,rear表示當前插入的點的父母
cout<<"請按正確順序輸入二叉樹的數據:";
cin.getline(t,1000); //先把輸入的數據輸入到一個t數組
//cout<<t<<" "<<endl;
int n1=strlen(t); //測量數據的長度
n=0;
for(i=0;i<n1;i++)
{
if(t[i]!='#')
{
p=NULL;
if(t[i]!=',') //滿足條件並開辟內存
{
n++;
p=new ECS_data;
p->data=t[i];
p->l=NULL;
p->r=NULL;
}
front++;
temp[front]=p;
if(1 == front){root=p;}
else
{
if((p!=NULL)&&(0==front%2))
{
temp[rear]->l=p;//剛開始把這裡寫成了==
}
if((p!=NULL)&&(1==front%2))
{
temp[rear]->r=p;
}
if(1==front%2)rear++; //就當前的數據找這個數據的父母
}
}
}
}
~ECS() //釋放內存
{
int i;
for(i=1;i<=n;i++)
if(temp[i]!=NULL)
delete temp[i];
}
void JS() //記錄節點的個數
{
int s;
s=n;
cout<<"該二叉樹的節點數為:"<<s<<endl;
}

void BL1(ECS_data *t)//先序遍歷
{
if(NULL!=t)
{
cout<<t->data<<",";
BL1(t->l);
BL1(t->r);
}
}
void BL2(ECS_data *t)//中序遍歷
{
if(NULL!=t)
{
BL2(t->l);
cout<<t->data<<",";
BL2(t->r);
}
}
void BL3(ECS_data *t)//後續遍歷
{
if(NULL!=t)
{
BL3(t->l);
BL3(t->r);
cout<<t->data<<",";
}
}
};

int main()
{
ECS a;
a.JS();
a.BL1(a.root);
cout<<endl;
a.BL2(a.root);
cout<<endl;
a.BL3(a.root);
cout<<endl;
return 0;
}

Copyright © Linux教程網 All Rights Reserved