Lec 13 TreesI
Lec 13 TreesI
Lec 13 TreesI
Slides by
Mohamed El-Ramly, PhD
Basheer Youssef, PhD
Agenda
1. Introduction to Binary Trees
2. Implementing Binary Trees
3. Searching Binary Search Trees
4. Tree Traversal …1. Breadth-First ….2. Depth-First
5. Insertion
6. ……1. Deletion by Merging …..2. By Copying
7. ……2. Balanced Trees
8. .
9. Heaps / Heap Sort
10. .
2
6.1 Trees
1. Linked Lists are limited, why?
2. Arrays?
• Advantages?
• Limitations?
3. Linked Structures?
Building Binary Trees w Arrays
Building Binary Trees w Nodes
Building Binary Trees w Nodes
(A few comments on style)
private
Chapter 6: Binary Trees 14
template <class T>
class BSTNode {
private:
T key;
BSTNode* left;
BSTNode* right;
public:
BSTNode () {left = right = 0;}
BSTNode (T& el, BSTNode* l = 0, BSTNode* r =
0){
key = el;
left = l;
right = r;
}
BSTNode* getLeft {return left;}
BSTNode* getRight {return right;}
T getKey {return key;}
template <class T>
class BST {
protected:
BSTNode<T>* root
public:
BST () {root = 0;}
void clear() {root = 0;}
bool isEmpty() {retun root == 0;}
T* search (T& el) {
BSTNode<T>* p = root;
while (p != 0)
if (el == p->getKey())
return &p->getKey();
else if (el < p->getKey())
p = getLeft();
else p = getRight();
return 0;
}
6.3 Searching in a BST
1. Trace searching for 1, 12, 31
2. What is the max num of tests
when searching in this tee?
Complexity of Searching in a BST
1. Measured by the number of comparisons done,
which depends on the nodes encountered on
the path from the root to the node searched for.
2. So, complexity is the length of the path leading
to this node +1;
3. = log n
4. Worst case = n