递归查找结点
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
class Node
{
public:
int data;
Node *lchild, *rchild, *father;
Node(int _data, Node *_father=NULL){
data = _data;
lchild = NULL;
rchild = NULL;
father = _father;
}
~Node(){
if(lchild != NULL)
delete lchild;
if(rchild != NULL)
delete rchild;
}
void myInsert(int value){
if(data == value)
return;
else if(data > value){
if(lchild == NULL)
lchild = new Node(value, this);
else
lchild->myInsert(value);
}
else{
if(rchild == NULL)
rchild = new Node(value, this);
else
rchild->myInsert(value);
}
}
Node *mySearch(int value){
if(value == data)
return this;
else if(value < data){
if(lchild == NULL)
return NULL;
else
return lchild->mySearch(value);
}
else{
if(rchild == NULL)
return NULL;
else
return rchild->mySearch(value);
}
}
void inOrder(){
if(lchild != NULL)
lchild->inOrder();
cout<<data<<" ";
if(rchild != NULL)
rchild->inOrder();
}
};
class BinaryTree
{
private:
Node *root;
public:
BinaryTree(){
root = NULL;
}
~BinaryTree(){
if(root != NULL)
delete root;
}
void myInsert(int value){
if(root==NULL)
root = new Node(value);
else
root->myInsert(value);
}
void inOrder(){
if(root != NULL)
root->inOrder();
else
cout<<"binarytree is empty!!!";
}
bool myFind(int value){
if(root->mySearch(value) != NULL)
return true;
else
return false;
}
};
int main(){
BinaryTree binarytree;
int arr[] = {-10, -2, 5, -11, -3, 22, 2333, 6, 0, 4};
for(int i=0; i<10; i++)
binarytree.myInsert(arr[i]);
binarytree.inOrder();
cout<<endl;
if(binarytree.myFind(2333))
cout<<"存在"<<endl;
else
cout<<"不存在"<<endl;
system("pause");
return 0;
}
如有疑惑或错误,欢迎提出,谢谢