Lecture_7 Binary Search Tree-studywing.blogspot.com.pdf - Google ...

0 downloads 157 Views 122KB Size Report
There was a problem previewing this document. Retrying... Download. Connect more apps... Try one of the apps below to op
Binary Search Tree

Search From a Tree • How much time it takes? • In order to search an element from the tree of n nodes, we may have to perform maximum n comparison. • What are the advantages of storing data in the form of tree? • Move towards search tree.

Binary Search Tree •

A binary tree that is either empty or in which every node contains a key and satisfies the conditions: I.

The key in the left child of a node (if it exists) is less than the key in its parent II. The key in the right child of a node (if it exists) is greater than the key in its parent node. III. The left and right sub-trees of the root are again binary search trees.



Keys in a binary search tree can be regarded as already sorted into order

Making a Binary Search Tree 4

15

20

15

null

15 4

17 15

15 4

20

15

19

4

4 20

17

20 17 19

Binary Search Tree Examples Binary Search Trees: What about this tree?

6 2

8

1

4 3 6

What about this tree?

2

8

1

4 3

7

Implementation of Binary Search Tree class BTNode{ public: int data; BTNode *left,*right; BTNode (int d,BTNode* l=NULL, BTNode* r=NULL) {data=d;left=l; right=r;} };

Implementation of Binary Search Tree class BST{ BTNode * root; public: BST(){root=NULL;} void InsertKey(int x); void InsertRKey(int x,BTNode* & B); void Inorder(BTNode* bt); void Preorder(BTNode* bt); void Postorder(BTNode* bt); BTNode* &RRoot(){return root;} void deleteNode(BTNode *BT); BTNode* SearchKey(int d); ~ BST( ); }

Continue on next slide…

Deleting a Binary Search Tree void BST::deleteNode(BTNode *BT) { if(BT!=NULL) { deleteNode(BT->left); deleteNode(BT->right); coutdata) else } }

Cur=Cur->left; Cur=Cur->right; Pre->left =pZ; Pre->right=pZ;

BST Insertion (Recursive) void BST:: InsertRKey(int x, BTNode* & B) { if(B==NULL) B=new BTNode(x); else if(x < B->data) InsertRKey(x,B->left); else InsertRKey(x,B->right); }

Driver int main ( ) { BST b1; int d; BTNode * Temp; while(1) { coutd; if(d==0) break; b1.InsertRKey(d , b1.RRoot()); } cout