Vous êtes sur la page 1sur 3

Binary Search Tree

In computer science, a binary search tree (BST) is a node based binary tree data structure which has the following propertieshttp://en.wikipedia.org/wiki/Binary_search_tree - cite_note-0:

The left sub tree of a node contains only nodes with keys less than the node's key. The right sub tree of a node contains only nodes with keys greater than the node's key. Both the left and right sub trees must also be binary search trees.

From the above properties it naturally follows that:

Each node (item in the tree) has a distinct key.

Generally, the information represented by each node is a record rather than a single data element. However, for sequencing purposes, nodes are compared according to their keys rather than any part of their associated records. The major advantage of binary search trees over other data structures is that the related sorting algorithms and search algorithms such as in-order traversal can be very efficient. In this program, now till we have done that to find the preorder, in-order and post-order of the given (that is inserted by the user) elements. Implementation of binary search tree #include<iostream.h> #include<conio.h> #include<stdio.h> #include<stdlib.h> struct node { int data; node *left; node *right; }; node *tree=NULL; node *insert(node *tree,int ele); void preorder(node *tree); void inorder(node *tree); void postorder(node *tree); int count=1; void main()

{ clrscr(); int ch,ele; do { clrscr(); cout<<"\n\t\a\a1----INSERT A NODE IN A BINARY TREE.\a\a"; cout<<"\n\t\a\a2----PRE-ORDER TRAVERSAL.\a\a"; cout<<"\n\t\a\a3----IN-ORDER TRAVERSAL.\a\a"; cout<<"\n\t\a\a4----POST-ORDER TRAVERSAL.\a\a"; cout<<"\n\t\a\a5----EXIT.\a\a"; cout<<"\n\t\a\aENTER CHOICE::\a\a"; cin>>ch; switch(ch) { case 1: cout<<"\n\t\a\aENTER THE ELEMENT::\a\a"; cin>>ele; tree=insert(tree,ele); break; case 2: cout<<"\n\t\a\a****PRE-ORDER TRAVERSAL OF A TREE****\a\a"; preorder(tree); break; case 3: cout<<"\n\t\a\a****IN-ORDER TRAVERSAL OF A TREE****\a\a"; inorder(tree); break; case 4: cout<<"\n\t\a\a****POST-ORDER TRAVERSAL OF A TREE****\a\a"; postorder(tree); break; case 5: exit(0); } }while(ch!=5); } node *insert(node *tree,int ele) { if(tree==NULL) {

tree=new node; tree->left=tree->right=NULL; tree->data=ele; count++; } else if(count%2==0) tree->left=insert(tree->left,ele); else tree->right=insert(tree->right,ele); return(tree); } void preorder(node *tree) { if(tree!=NULL) { cout<<tree->data; preorder(tree->left); preorder(tree->right); getch(); } } void inorder(node *tree) { if(tree!=NULL) { inorder(tree->left); cout<<tree->data; inorder(tree->right); getch(); } } void postorder(node *tree) { if(tree!=NULL) { postorder(tree->left); postorder(tree->right); cout<<tree->data; getch();} }

Vous aimerez peut-être aussi