是使用c++写的
#include<iostream>
using namespace std;
//二叉树节点的定义
class BichaTreeNode{
private:
int data; //数据
public:
BichaTreeNode *left; //左节点
BichaTreeNode *right; //右节点
BichaTreeNode(int myData){ //二叉树节点的构造
data=myData;
left=NULL;
right=NULL;
}
int getData(){ //访问节点数据
return data;
}
void insertNewNode(BichaTreeNode *newNode){
if(data <= newNode->getData()) {
if(this->right != NULL)
this->right->insertNewNode(newNode);
else
this->right=newNode;
}else{
if(this->left != NULL)
this->left->insertNewNode(newNode);
else
this->left=newNode;
}
}
void traveral() { //二叉树的中序遍历
if(this!=NULL) {
this->left->traveral();
cout<<this->getData()<<"\t";
this->right-> traveral();
}
}
void preTraveral() { //二叉树前序遍历
if(this!=NULL) {
cout<<this->getData()<<"\t";
this->left->preTraveral();
this->right->preTraveral();
}
}
void postTraveral() { //二叉树的后续遍历
if(this!=NULL) {
this->left->postTraveral();
this->right->postTraveral();
cout<<this->getData()<<"\t";
}
}
BichaTreeNode * findData(int aim) { //查找算法
if(this==NULL)
return NULL;
else if(this->getData()==aim)
return this;
else {
if(aim>this->getData())
return this->right->findData(aim);
else
return this->left->findData(aim);
}
}
};
//二叉树的的定义
class BichaTree{
private:
BichaTreeNode *root; //二叉树的跟节点
public:
BichaTree(){ //二叉树的构造
root = NULL;
}
void addNode(int data){ //二叉树节点的插入
BichaTreeNode *node = new BichaTreeNode(data);
if(root == NULL)
root=node;
else
root->insertNewNode(node);
}
BichaTreeNode * getRoot(){ //访问根节点
return root;
}
void preView(){ //二叉树的前序遍历
root->preTraveral();
}
void inView(){ //二叉树的中序遍历
root->traveral();
}
void postView() {
root->postTraveral();
}
void find(int number){ //二叉树查找
if(root->findData(number) !=NULL)
cout<<"该数据的地址是"<< root->findData(number)<<endl;
else
cout<<"没有该数据!";
}
};
//主方法测试
int main(){
BichaTree *b=new BichaTree();
b->addNode(9);
b->addNode(5);
b->addNode(10);
b->addNode(30);
b->addNode(2);
b->addNode(40);
b->addNode(80);
b->addNode(8);
b->addNode(1);
b->addNode(7);
b->addNode(6);
// b->addNode(100);
// b->addNode(15);
cout<<"前序遍历:";
b->preView();
cout<<"\n";
cout<<"中序输出:";
b->inView();
cout<<"\n";
cout<<"后续序输出:";
b->postView();
b->find(30);
return 0;
}