CmSc 250 Intro to Algorithms
Binary Search Trees
Learning goals
Exam-like questions
Binary Search Trees
The left subtree of each node contains values that are smaller than the value in the given node.
The right subtree of each node contains values that are greater than the value in the given node.
Example:
Operations:
The idea behind is: all the values to the right are
greater than all the values to the left,
so the smallest one
will be greater too (i.e. after the replacement its left subtree
will contain smaller values.) And since we have taken the
smallest from the right subtree,
after the replacement the
right subtree will contain only greater values.
Creating a binary search tree:
Initially the tree is empty.
The first element to be stored is placed in a node that would be
the root of the tree.
Each next element is placed through the "unsuccessful search"
procedure.
Retrieving the elements in sorted order - by in-order traversal.
Complexity of search in a binary tree: O(logN)
The search at worst will proceed to the leaves, down a path in
the tree.
On average the depth of a binary tree with N
elements is log(N).
This is not the worst case though. The worst case is when
the items to be inserted
are sorted, then the tree degenerates
to a list:
The tree is not balanced.
Disadvantages of Binary Search Trees:
Improving the efficiency of Binary Search Trees:
Learning goals:
- Know what a Binary Search Tree (BST) is - how the keys are located (smaller to the left, greater to the right).
- Be able to describe how a BST is created and how we search for a key.
- Be able to discuss the complexity of BST operations.
- Know the advantages and disadvantages of Binary Search Trees.
Exam-like questions:
- What is a Binary Search Tree, how are the keys located?
- How are the elements in a Binary Search Tree retrieved in sorted order?
- What is the complexity of search and insert operations in a BST?
- What is the complexity of creating a BST?
- Discuss the advantages and disadvantages of Binary Search Trees.
- Given a sequence of letters to serve as keys, draw the corresponding binary search tree.