#include "binarytree.h"
 Node_Ptr BinaryTree::treeSearch(Node_Ptr t, int x){
 if((t == NULL)|| (t->key == x))
  return t;
 if(x< t->key)
   return treeSearch(t->left,  x);
 treeSearch(t->right, x);
 
 }
void BinaryTree::getData(int *input, int n){
  for(int i=0;i<n;i++){
  input[i]=rand()%(2*n); 
  
   }
cout<<"Before"<<endl;
    for(int i=0;i<n;i++){
  cout<<input[i]<<" ";
   }
  
 }
void BinaryTree::searchData(int x){
  Node_Ptr searchData=(Node_Ptr)new Node;
  searchData=treeSearch(root, x);
  if(searchData==NULL){
  cout<<"not found";
  }
  else
  {
   cout<<"found:"<<x;
  }
  
cout<<endl;
 }
Node_Ptr BinaryTree::treeInsert(Node_Ptr t, int x){
Node_Ptr r;
r=(Node_Ptr)new Node;
 if(t==NULL){
  r->key=x;
  r->left=NULL;
  r->right=NULL;
  return r;
 }
if(x<t->key)
 {t->left=treeInsert((t->left),x); 
 return t;}
 else
 {t->right=treeInsert((t->right),x);
 return t;}
}
void BinaryTree::insertData(int *input, int n){
root=NULL;
for(int i=0;i<n;i++){
root=treeInsert(root,input[i]);
cout<<"root:"<<root->key;
print(root);
 }
 
cout<<endl;
}
void BinaryTree::print(Node_Ptr x){
 if(x!=NULL){
  print(x->left);
  cout<<x->key<<" ";
  print(x->right);
 
 }
}
-------------------bianrytree.cpp
#ifndef BINARYTREE_H
#define BINARYTREE_H
#include <iostream>
using namespace std;
typedef class Node *Node_Ptr;
class Node {
public:
 int key;
 Node_Ptr left;
 Node_Ptr right;
 Node_Ptr parent;
};
 class BinaryTree{
 private:
  Node_Ptr root;
 public:
  void getData(int *input, int n);
  void insertData(int *input, int n);
  void searchData(int x);
  void print(Node_Ptr x);
  Node_Ptr treeInsert(Node_Ptr t, int x);
  Node_Ptr treeSearch(Node_Ptr t, int x);
};
#endif
--------------.h
#include <iostream>
#include"binarytree.h"
using namespace std;
int main(){
 BinaryTree b;
 int *input, n, x;
 cout<<"Enter N=";
 cin>>n;
 input = new int [n];
b.getData(input,n);
cout<<endl;
 b.insertData(input, n);
 cout<<"x를 입력하시오";
 cin>>x;
b.searchData(x);
 system("PAUSE");
 return 0;
}
----------main
'Not Using > algorithm' 카테고리의 다른 글
| DP (0) | 2009.12.01 | 
|---|---|
| Dynamic programming (0) | 2009.11.17 | 
| 해쉬테이블 완성 (0) | 2009.11.09 | 
| 완성못한 해쉬테이블 (0) | 2009.11.03 | 
| 알고리즘 --- (0) | 2009.10.13 |