二叉樹的鏈式結構
阿新 • • 發佈:2018-12-08
#ifndef Tree_H
#define Tree_H
const int Max=20;
struct TNode
{
char data;
TNode *leftchild,*rightchild;
};
class Tree
{
public:
Tree(){root=Creat(root);}
~Tree(){Release(root);}
void PreOrder(){PreOrder(root);}
void InOrder(){InOrder(root);}
void PostOrder(){PostOrder(root);}
private:
TNode *root;
TNode *Creat(TNode *bt);
void Release(TNode *bt);
void PreOrder(TNode *bt);
void InOrder(TNode *bt);
void PostOrder(TNode *bt);
};
char ch;
cout<<"請輸入建立一顆二叉樹的結點資料"<<endl;
cin>>ch;
if(ch=='#')return NULL;
else{
bt=new TNode;
bt->data=ch;
bt->leftchild=Creat(bt->leftchild);
bt->rightchild=Creat(bt->rightchild);
}
return bt;
}
void Tree::Release(TNode *bt)
{
if (bt==NULL) return;
else
{
Release(bt->leftchild);
Release(bt->rightchild);
delete bt;
}
}
void Tree::PreOrder(TNode *bt)
{
if(bt==NULL) return;
else
{
cout<<bt->data;
PreOrder(bt->leftchild);
PreOrder(bt->rightchild);
}
}
void Tree::InOrder(TNode *bt)
{
if(bt==NULL)return;
else{
InOrder(bt->leftchild);
cout<<bt->data<<" ";
InOrder(bt->rightchild);
}
}
void Tree::PostOrder(TNode *bt)
{
if(bt==NULL) return;
else
{
PostOrder(bt->leftchild);
PostOrder(bt->rightchild);
cout<<bt->data;
}
}
#include<iostream>
using namespace std;
#include"LinklistTree.h"
int main()
{
Tree t1;
cout<<"---前序遍歷---"<<endl;
t1.PreOrder();
cout<<endl;
cout<<"---中序遍歷---"<<endl;
t1.InOrder();
cout<<endl;
cout<<"---後序遍歷---"<<endl;
t1.PostOrder();
cout<<endl;
return 0;
}
#define Tree_H
const int Max=20;
struct TNode
{
char data;
TNode *leftchild,*rightchild;
};
class Tree
{
public:
~Tree(){Release(root);}
void PreOrder(){PreOrder(root);}
void InOrder(){InOrder(root);}
void PostOrder(){PostOrder(root);}
private:
TNode *root;
TNode *Creat(TNode *bt);
void Release(TNode *bt);
void PreOrder(TNode *bt);
void PostOrder(TNode *bt);
};
#endif
#include<iostream>
using namespace std;
#include "LinklistTree.h"
TNode *Tree::Creat(TNode *bt)
{
cout<<"請輸入建立一顆二叉樹的結點資料"<<endl;
cin>>ch;
if(ch=='#')return NULL;
else{
bt=new TNode;
bt->data=ch;
bt->leftchild=Creat(bt->leftchild);
bt->rightchild=Creat(bt->rightchild);
}
return bt;
}
void Tree::Release(TNode *bt)
{
if (bt==NULL) return;
else
{
Release(bt->leftchild);
Release(bt->rightchild);
delete bt;
}
}
void Tree::PreOrder(TNode *bt)
{
if(bt==NULL) return;
else
{
cout<<bt->data;
PreOrder(bt->leftchild);
PreOrder(bt->rightchild);
}
}
void Tree::InOrder(TNode *bt)
{
if(bt==NULL)return;
else{
InOrder(bt->leftchild);
cout<<bt->data<<" ";
InOrder(bt->rightchild);
}
}
void Tree::PostOrder(TNode *bt)
{
if(bt==NULL) return;
else
{
PostOrder(bt->leftchild);
PostOrder(bt->rightchild);
cout<<bt->data;
}
}
#include<iostream>
using namespace std;
#include"LinklistTree.h"
int main()
{
Tree t1;
cout<<"---前序遍歷---"<<endl;
t1.PreOrder();
cout<<endl;
cout<<"---中序遍歷---"<<endl;
t1.InOrder();
cout<<endl;
cout<<"---後序遍歷---"<<endl;
t1.PostOrder();
cout<<endl;
return 0;
}