/* Binary Search Tree */
/* @BEGIN_OF_SOURCE_CODE */
#include <stdio.h>
#include <stdlib.h>
struct tree_node
{
struct tree_node *left ;
struct tree_node *right ;
struct tree_node *parent ;
int key ;
};
typedef struct tree_node *TREENODEPTR ;
TREENODEPTR bst_search(TREENODEPTR r, int k)
{
while (r != NULL && k != r->key)
if (k < r->key) r = r->left ;
else r = r->right ;
return r ;
}
/*
r : points to root of the tree
n : pointer to the new node to be inserted
*/
void bst_insert(TREENODEPTR *r, TREENODEPTR n)
{
TREENODEPTR p = NULL ;
TREENODEPTR x = *r ;
while (x != NULL) {
p = x ;
if (n->key < x->key)
x = x->left ;
else x = x->right ;
}
n->parent = p ;
if (p == NULL)
*r = n ;
else if (n->key < p->key)
p->left = n ;
else p->right = n ;
}
void clear(TREENODEPTR r)
{
if (r==NULL)
return ;
if (r->left) clear(t, r->left) ;
if (r->right) clear(t, r->right) ;
free(r) ;
}
int main()
{
int n ;
TREENODEPTR root, tmp ;
#ifndef ONLINE_JUDGE
freopen("bst.in", "r", stdin) ;
#endif
root = NULL ;
while (scanf("%d", &n) != EOF) {
if ((tmp = bst_search(root, n)) == NULL) {
tmp = (TREENODEPTR) malloc(sizeof(struct tree_node)) ;
tmp->key = n ;
tmp->left = NULL ;
tmp->right = NULL ;
tmp->parent = NULL ;
bst_insert(&root, tmp) ;
}
else {
printf("Element [%d] already exists\n", n) ;
}
}
if (root) {
clear(root) ;
free(root) ;
}
return 0;
}
/* @END_OF_SOURCE_CODE */
Pages
Labels
01 Knapsack
(1)
Ad Hoc
(1)
Backtracking
(1)
Binary Search Tree
(1)
bits
(1)
Brute Force
(1)
codelib
(2)
Data Structures
(1)
Dijkstra
(1)
DP
(2)
Graphs
(1)
Heaps
(1)
Joseph
(1)
Maximum 1-D Sum
(1)
Maximum Contiguous Sum
(1)
Primes
(1)
Priority Queues
(1)
Recursion
(1)
Sieve of Atkins
(1)
UVaOJ Vol-102
(1)
UVaOJ Vol-109
(1)
UVaOJ Vol-5
(1)
Monday, January 24, 2011
Binary Search Tree
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment