//二叉查找树
#include<iostream>
using namespace std;
class Node{
public:
// int index;//索引
int data;
Node *pLchild;
Node *pRchild;
Node();
void Addnode(int x,Node *&p);
int Find(int x,Node *p,int &count);
void insubtree(Node*node);
};
Node::Node() {
data=0;
pLchild=NULL;
pRchild=NULL;
}
void Node::Addnode(int x,Node *&p) {
if(!p){
p=new Node();
p->data =x;
p->pLchild =p->pRchild =NULL;
}
else{
if(x<p->data ){
Addnode(x,p->pLchild);
}
else if(x>p->data){
Addnode(x,p->pRchild);
}
}
}
int Node::Find(int x,Node *p,int &count){
if(p==NULL) return 0;
count+=1;
if(x==p->data ) return count;
else if(x>p->data ) Find(x,p->pRchild ,count);
else if(x<p->data ) Find(x,p->pLchild ,count);
}
void Node::insubtree(Node*node)
{
if(node==NULL) return;
insubtree(node->pLchild);//先遍历左子树
cout<<node->data<<" ";//输出根节点
insubtree(node->pRchild);//再遍历右子树
}
class Tree{
public:
Tree(int data);
~Tree();
void Addnode(int x);
int Find(int x);
void insubtree();
private:
Node *pRoot;
};
Tree::Tree(int data){
pRoot=new Node();
pRoot->data=data;
pRoot->pLchild =NULL;
pRoot->pRchild =NULL;
}
void Tree::Addnode(int x){
pRoot->Addnode(x,pRoot);
}
int Tree::Find(int x) {
int count=0;
pRoot->Find(x,pRoot,count);
}
void Tree::insubtree() {
pRoot->insubtree(pRoot);
}
int main(){
int n;
cin>>n;
Node a[n];
cin>>a[0].data ;
Tree *tree=new Tree(a[0].data);
//34, 76, 45, 18, 26, 54, 92, 65
for(int i=0;i<n-1;i++){
cin>>a[i+1].data;
tree->Addnode(a[i+1].data);
}
tree->insubtree() ;
//int count=0;
cout<<tree->Find(76);
}
添加回答
举报
0/150
提交
取消