Binary Search Tree
Binary Search Tree
Definition
BST Rules
–the left subtree of x contains elements that are smaller than those stored in x,
–the right subtree of x contains all elements that are greater than those stored in x,
Binary Search Tree Operations
Search() : find key in the BST
Whenever an element is to be searched, start searching from the root node. Then if the data is less than the key value, search for the element in the left subtree. Otherwise, search for the element in the right subtree. Follow the same algorithm for each node.
Insert() : insert new key into BST
Whenever an element is to be inserted, first locate its proper location. Start searching from the root node, then if the data is less than the key value, search for the empty location in the left subtree and insert the data. Otherwise, search for the empty location in the right subtree and insert the data.
•There are 3 cases which should be considered:
If the key is in a leaf, just delete that node
If the key is in a node which has one child, delete that node and connect its child to its parent
If the key is in a node which has two children, find the right most child of its left sub tree (node P), replace its key with P’s key and remove P recursively. (or alternately you can choose the left most child of its right sub tree)
If the key is in a leaf, just delete that node
If the key is in a node which has one child, delete that node and connect its child to its parent
If the key is in a node which has two children, find the right most child of its left sub tree (node P), replace its key with P’s key and remove P recursively. (or alternately you can choose the left most child of its right sub tree)
Comments
Post a Comment