二叉树基本操作
二叉树的结构
struct Tnode{
Elem data;
Tnode *lch,*rch;
Tnode(int val){
data = val;
lch=NULL;
rch=NULL;
}
};
二叉树的建立(先序输入)
void BinTreeInput(Tnode *&root){
Elem x;
cin>>x;
if(x==-1){
root=NULL;
}else{
root = new Tnode(x);
BinTreeInput(root->lch);
BinTreeInput(root->rch);
}
}
注:如何建立二叉树应根据数据的输入方式变化
先序遍历输出
void BinTreePreorder(const Tnode *root){//先序遍历输出
if(root){
printf("%d ",root->data);
BinTreePreorder(root->lch);
BinTreePreorder(root->rch);
}
}
中序遍历输出
void BinTreeInorder(const Tnode *root){//中序遍历输出
if(root){
BinTreeInorder(root->lch);
printf("%d ",root->data);
BinTreeInorder(root->rch);
}
}
后序遍历输出
void BinTreePostorder(const Tnode *root){//后续遍历输出
if(root){
BinTreePostorder(root->lch);
BinTreePostorder(root->rch);
printf("%d ",root->data);
}
}
二叉树的删除操作
void BinTreeDestroy(Tnode *root){//二叉树的删除操作
if (root) {
// 递归释放左子树和右子树
BinTreeDestroy(root->lch);
BinTreeDestroy(root->rch);// 释放当前节点
delete root;
cout<<"释放一个结点"<<endl;
root = NULL;
}
}
方法一:用结构体实现
实现代码:
#include<iostream>
using namespace std;
typedef int Elem;
struct Tnode{
Elem data;
Tnode *lch,*rch;
Tnode(int val){
data = val;
lch=NULL;
rch=NULL;
}
};
void BinTreeCreate(Tnode *&root){
root=NULL;
}
void BinTreeInput(Tnode *&root){
Elem x;
cin>>x;
if(x==-1){
root=NULL;
}else{
root = new Tnode(x);
BinTreeInput(root->lch);
BinTreeInput(root->rch);
}
}
void BinTreePreorder(const Tnode *root){//先序遍历输出
if(root){
printf("%d ",root->data);
BinTreePreorder(root->lch);
BinTreePreorder(root->rch);
}
}
void BinTreeInorder(const Tnode *root){//中序遍历输出
if(root){
BinTreeInorder(root->lch);
printf("%d ",root->data);
BinTreeInorder(root->rch);
}
}
void BinTreePostorder(const Tnode *root){//后续遍历输出
if(root){
BinTreePostorder(root->lch);
BinTreePostorder(root->rch);
printf("%d ",root->data);
}
}
void BinTreeDestroy(Tnode *root){//二叉树的删除操作
if (root) {
// 递归释放左子树和右子树
BinTreeDestroy(root->lch);
BinTreeDestroy(root->rch);// 释放当前节点
delete root;
cout<<"释放一个结点"<<endl;
root = NULL;
}
}
int main(){
Tnode *r;
BinTreeCreate(r);
BinTreeInput(r);
cout<<"先序输出结果:";
BinTreePreorder(r);
cout<<endl;
cout<<"中序输出结果:";
BinTreeInorder(r);
cout<<endl;
cout<<"后序输出结果:";
BinTreePostorder(r);
cout<<endl;
BinTreeDestroy(r);//二叉树的删除操作
return 0;
}