網頁

2012年7月19日 星期四

d526: Binary Search Tree (BST)

~/Desktop/kk.cpp.html
/**********************************************************************************/
/*  Problem: d526 "Binary Search Tree (BST)" from BST                             */
/*  Language: CPP (950 Bytes)                                                     */
/*  Result: AC(80ms, 1.6MB) judge by this@ZeroJudge                               */
/*  Author: monkey413 at 2012-07-19 13:32:31                                      */
/**********************************************************************************/
#include<iostream>
#include<cstdlib>
using namespace std ;
class Node
{
    public:
        int value ;
        Node* left;
        Node* right;
};
Node* root;

void Add_Node_To_Tree(Node** curr, int data)
{
    if(*curr==NULL)
    {
        Node* tmp=new node ;
        //tmp=(Node*)malloc(sizeof(Node)); 
        tmp->value=data,tmp->left=NULL,tmp->right=NULL ;
        *curr=tmp ;
    }
    else if(data<(*curr)->value) Add_Node_To_Tree(&((*curr))->left,data) ;
    else if(data>(*curr)->value) Add_Node_To_Tree(&((*curr))->right,data);
}
void pre(Node* ptr)
{
    if(ptr!=NULL)
    {
        cout << ptr->value << " " ;
        pre(ptr->left) ;
        pre(ptr->right) ;
    }
}
int n ;
int main()
{
    while(cin>>n)
    {
        int num[n] ;
        root=NULL ;
        for(int i=0 ; i<n ; ++i) cin >> num[i], Add_Node_To_Tree(&root,num[i]) ;
        pre(root) ;
        cout << endl ;
    }
    return 0;
}

沒有留言:

張貼留言