最基本的二叉链表的构建:
废话不多说,先上代码:
声明:看懂此代码需要有一定的C++面向对象的基础,要对结构体和指针有一定的了解,当然啦,基本的函数定义再不会的话,可以回炉重造了,开个玩笑啦~~
#include<iostream>
#include<string>
using namespace std;
template <class DataType>
struct BiNode
{
DataType data;
BiNode<DataType> *lchild,*rchild;
};
template <class DataType>
class BiTree
{
public:
BiTree(){root=Creat();}
~BiTree(){Release(root);}
void Preorder(){Preorder(root);}
void Inorder(){Inorder(root);}
void Postorder(){Postorder(root);}
//void Levelorder();
private:
BiNode<DataType> *root;
BiNode<DataType> *Creat();
void Release(BiNode<DataType> *bt);
void Preorder(BiNode<DataType> *bt);
void Inorder(BiNode<DataType> *bt);
void Postorder(BiNode<DataType> *bt);
};
template<class DataType>
BiNode<DataType> *BiTree<DataType>::Creat()//返回类型就是节点类型,所以根本不需要再传一个节点类型的参数
{
BiNode<DataType> *bt;
char ch;
cin>>ch;
if(ch=='#')
bt=NULL;
else
{
bt=new BiNode<DataType>;
bt->data=ch;
bt->lchild=Creat();
bt->rchild=Creat();
}
return bt;
}
template <class DataType>//析构函数调用的清理函数
void BiTree<DataType>::Release(BiNode<DataType> *bt)
{
if(bt!=NULL)
{
Release(bt->lchild);
Release(bt->rchild);
delete bt;
}
}
template <class DataType>
void BiTree<DataType>::Preorder(BiNode<DataType> *bt)
{
if(bt==NULL)
return;
else
{
cout<<bt->data<<" ";
Preorder(bt->lchild);
Preorder(bt->rchild);
}
}
template <class DataType>
void BiTree<DataType>::Inorder(BiNode<DataType> *bt)
{
if(bt==NULL)
return;
else
{
Inorder(bt->lchild);
cout<<bt->data<<" ";
Inorder(bt->rchild);
}
}
template <class DataType>
void BiTree<DataType>::Postorder(BiNode<DataType> *bt)
{
if(bt==NULL)
return;
else
{
Postorder(bt->lchild);
Postorder(bt->rchild);
cout<<bt->data<<" ";
}
}
int main()
{
cout<<"请创建二叉树"<<endl;
BiTree<char> bi;
cout<<"----------------------------------------前序遍历-------------------------------------"<<endl;
bi.Preorder();
cout<<endl;
cout<<"---------------------------------------中序遍历-------------------------------------"<<endl;
bi.Inorder();
cout<<endl;
cout<<"----------------------------------------后序遍历-------------------------------------"<<endl;
bi.Postorder();
cout<<endl;
return 0;
}
简要说明和分析
这段代码完成了二叉链表的构造、先序遍历、中序遍历、后序遍历,与离散数学中对二叉树的操作密切相关,感兴趣的朋友可以顺便了解一下二叉树,其中有关二叉树的性质对以后的解题很有帮助。关于二叉树的性质会在后面进行更新。
注意的地方
1、二叉树乃至整个树的核心思想就是递归,所以在创建二叉链表和遍历的时候都使用了递归的思想
2、定义Crreat()的时候返回的是BiNode节点类型,不需要在参数里再传一个节点类型的参数,这点一定要注意,在有些教材中,会出现既有返回值又有实参的情况,一定要注意!!
3、注意定义BiNode类型的根节点,这个节点相当于单链表的头结点,与下面所传的参数不相同。
4、注意定义模板的时候,要加上固定的模板头部,template<class DataType>。
5、其实说白了,最基本的三种遍历方法的区别就是头结点的输出位置不一样,前序遍历在前,中序遍历在中,后在后。
6、与单链表不一样的是就两点,一个是定义root节点(其实没什么区别),再就是Creat()函数也要定义为节点类型。
其他的感觉没什么,因为不是很难,原谅我语文功底不行,文字叙述很一般。大佬们见谅啊~~~~~~有错误尽管指出来就好,不用给我留面子,但是不接受恶意的昂~~~