3. Preliminaries
Tree
A collection of nodes
The collection can be empty
Otherwise, the tree consists of a distinguished
node r, called the root, and zero or more
(sub)trees T1, T2, T3, …, Tk, each of whose
roots are connected by a directed edge to r.
The root of each subtree is said to be a child
of r, and r is the parent of each subtree root
5. Preliminaries
Tree
A tree is a collection of n nodes, one of which
is the root, and n-1 edges.
Each edge connects some node to its parent and
every node except the root has one parent
6. Preliminaries
ROOT
A
INTERNAL NODES INTERNAL NODES
B C D E F G
LEAF LEAF
H I J L M N O
LEAF LEAF LEAVES
P Q
LEAVES
7. Binary Tree
A binary tree is a tree in which no node
can have more than two children
root
TL TR
11. Binary Search Tree
An application of binary trees is their use in
searching
Let us assume that each node in the tree is
assigned a key value, and assume that this is an
integer
The property that makes a binary tree into a
binary search tree is that for every node, X, in
the tree, the values of all keys in the left subtree
are smaller than the key value in X, and the
values of all keys in the right subtree are larger
than the key value in X.
22. BST (Delete)
In deletion, we don’t ask for a position.
We ask for the actual item that has to be
deleted. Deleting a leaf
6
2 8
4 11
1
Deleting a node with one child
3
Deleting a node with two children
30. Discussion
We did not achieve our goal of log n.
Can we improve?
Always keep the tree balanced A
D E
H I J L
P Q
31. Adelson-Velski Landis (AVL)
Tree
An AVL tree is a binary search tree where
every node of the tree satisfies the
following property:
The height of the left and right subtrees of a
node differs by at most one.
33. Adelson-Velski Landis (AVL)
Tree
In order to properly implement the AVL, the node has to
be redefined.
class node{
public:
int item;
node *left;
node *right;
int height;
node(int x) { item = x; left = right = NULL; }
node( ) { item = 0; left = right = NULL; }
};
34. Adelson-Velski Landis (AVL)
Tree
What kinds of violations may occur in a regular
BST that will result in height imbalance?
1 3 3
2 2 1
3 1 2
43. Insert
void BST::insert(int x){
//do insert as in BST
current = x;
set current to balanced
do{
previous = x;
update height of current
lh = height of the left subtree of current
rh = height of the left subtree of current
set current as left leaning, right leaning, or balanced
if(violation occurs)
perform corresponding rotation
}while(??);
}