Binary Search Tree (BST)
Binary Search Tree (BST) Definition: “A BINARY SEARCH TREE is a binary tree in symmetric order.” A binary tree is either: empty a key-value pair and two binary trees [neither of which contain that key]
Binary Search Tree (BST) Symmetric order means that: every node has a key every node’s key is larger than all keys in its left subtree smaller than all keys in its right subtree
Difference between BT & BST A binary tree is simply a tree in which each node can have at most two children. Typically the first node is known as the parent and the child nodes are called left and right. A binary search tree is a binary tree in which the nodes are assigned values, with the following restrictions ; No duplicate values Left child node is smaller than its parent Node Right child node is greater than its parent Node BT BST
Binary Search Tree a b c d e g h i l f j k
Binary Search Tree Operations Creating a binary search tree Finding a node in a binary search tree Inserting a node into a binary search tree Deleting a node in a binary search tree Traversing a binary search tree.
Creating a Binary (Search) Tree We will use a simple class that implements a binary tree to store integer values We create a class called IntBinaryTree
A Node of BST
Finding a node in a binary search tree Find ( root, 2 )
Code
Inserting a node into a BST If a tree or sub-tree does not exist, create a node and insert the value in it. If the value we are inserting is less than the root of the tree we move to the left sub-tree and start at step 1 again. If the value is greater than the root of the tree we move to the right sub-tree and start at step 1 again. If the value is equal to the root of the tree or sub- tree we do nothing because the value is already there. In this case we return.
Example
Code
Deleting a Node in BST Algorithm Observation Perform search for value X If X is a leaf, delete X Else // must delete internal node Replace with largest value Y on left subtree OR smallest value Z on right subtree Delete replacement value (Y or Z) from subtree Observation Deletions may unbalance tree
Example Deletion (Leaf)
Example Deletion (Internal Node)
Traversal of Binary Trees Inorder Traversal (symmetric traversal) Preorder Traversal (depth first traversal) Postorder Traversal
InOrder Traversal Manner: Left Root Right Sorted
Code
InOrder ‘2’ ‘3’ ‘4’ ‘+’ ‘*’ What value does it have? ( 4 + 2 ) * 3 = 18
PreOrder Traversal Manner Root Left Right
Code
PostOrder Traversal Manner Left Right Root
Code