大家都知道二叉树最大的特点即只有两个节点,因此可以大致构建这一个二叉树类:
#ifndef TREE_H
#define TREE_H
class Tree
{
public:
int data; //value值
Tree *pleft;//左节点
Tree *pright;//右结点
Tree *pfather//父节点
Tree(int da=0);构造函数
void deleteNode();//删除一个节点函数
Tree *searchNode(int index);//查找一个节点函数
void priorTraverse();//先序遍历
void midiaTraverse();//中序遍历
void afterTraverse();//后序遍历
};
#endif
接下来就可以写对应的实现函数了:
1)首先是构造函数
Tree::Tree(int da) {
data = da;
pleft = NULL;
pright = NULL;
pfather=NULL;
}
2)节点删除函数
void Tree::deleteNode() {
if (this->pleft != NULL)
{
this->pleft->deleteNode();
}
if (this->pright != NULL) {
this->pright->deleteNode();
}
if (this->pfather != NULL) {
if (this->pfather->pleft == this)
this->pfather->pleft = NULL;
if (this->pfather->pright == this)
this->pfather->pright= NULL;
}
delete this;
}
3)节点查找函数
Tree *Tree::searchNode(int val) {
if (this->data== index) {
return this;
}
Tree *temp = NULL;
if (pleft != NULL) {
if (this->pleft->data== val)
return this->pleft;
else
{
temp = this->pleft->searchNode(val);
if (temp != NULL)
return temp;
}
}
if (pright != NULL) {
if (this->pright->data== val)
return this->pright;
else
temp=this->pright->searchNode(val);
return temp;
}
return NULL;
}
4)先序遍历
void Tree::priorTraverse() {
cout << data << endl;
if (this->pleft != NULL) {
this->pleft->priorTraverse();
}
if (this->pright != NULL) {
this->pright->priorTraverse();
}
}
5)中序遍历
void Tree::midiaTraverse() {
if (this->pleft != NULL) {
this->pleft->midiaTraverse();
}
cout << data << endl;
if (this->pright != NULL) {
this->pright->midiaTraverse();
}
}
6)后序遍历
void Tree::afterTraverse() {
if (this->pleft != NULL) {
this->pleft->afterTraverse();
}
if (this->pright != NULL) {
this->pright->afterTraverse();
}
cout<< data << endl;
}
这样大致一颗二叉树类就建立好了
测试:
#include<iostream>
#include”tree.h”
using namespace std;
int main()
{
Tree *root = new Tree(1);
root->pleft = new Tree(2);
root->pright = new Tree(3);
root->pleft->pfather = root;
root->pright->pfather = root;
root->pleft->pleft = new Tree(4);
root->pleft->pright = new Tree(5);
root->pleft->pleft->pfather = root->pleft;
root->pleft->pright->pfather = root->pleft;
root->pright->pleft = new Tree(6);
root->pright->pright = new Tree(7);
root->pright->pleft->pfather = root->pright;
root->pright->pright->pfather = root->pright;
root->priorTraverse();
cout << endl;
root->midiaTraverse();
cout << endl;
root->afterTraverse();
cout << endl;
Tree *node = root->searchNode(3);
cout << node->data << endl;
node->deleteNode();
root->priorTraverse();
cout << endl;
}