Download presentation
Presentation is loading. Please wait.
1
Binary Search Tree (BST)
2
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]
3
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
4
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
5
Binary Search Tree a b c d e g h i l f j k
6
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.
7
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
8
A Node of BST
9
Finding a node in a binary search tree
Find ( root, 2 )
10
Code
12
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.
13
Example
14
Code
15
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
16
Example Deletion (Leaf)
17
Example Deletion (Internal Node)
18
Traversal of Binary Trees
Inorder Traversal (symmetric traversal) Preorder Traversal (depth first traversal) Postorder Traversal
19
InOrder Traversal Manner: Left Root Right Sorted
20
Code
21
InOrder ‘2’ ‘3’ ‘4’ ‘+’ ‘*’ What value does it have?
( ) * 3 = 18
22
PreOrder Traversal Manner Root Left Right
23
Code
24
PostOrder Traversal Manner Left Right Root
25
Code
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.