8 Dsa
8 Dsa
Outline
❖ Tree Terminology
❖ Binary Trees
❖ Types of Binary Trees
❖ Some Q & A
❖ Expression Trees
❖ Tree Traversal
❖ Construction of Binary Tree
❖ Construction of Expression Trees and its Evaluation
❖ MCQs and Assignments
❖ Binary Search Trees (BST)
❖ Creation, Insertion & Deletion Operations on BSTs
❖ Height Balanced Trees (AVL Trees) (Insertion & Deletion)
❖ B-Trees and B+ Trees (Insertion & Deletion)
❖ Heap Trees (Max Heap & Min Heap)
❖ Assignments and Doubt Clearance
Why Study Trees???
They give the hierarchical relationship between
different elements.
Databases (B-TREES)
Data Compression (Huffman Trees)
Bitcoin (Merkle Trees)
Medical Diagnosis (Decision Trees)
Trees
A Tree is a special linked list-based data structure
that has many uses in Computer Science:
A Decision Tree
AAn A Does
Binary
FamilytheTree
Search Tree
• To organize hierarchical data Expression Tree
patient
• To make information easily have a+fever?
“marty”
“carey”
searchable yes no
• To simplify the evaluation of Does he/she Does he/she
mathematical expressions have “harry”
spots
* on
“leon”
his/her face?
have +
a sore
“andrea”
“rich”
throat?
• To make decisions
yes
“sheila”
“alan”
He has 32 …
“simon”
“jacob” -42 “milton”
17 “martha”
“nancy” “zai”
4
COOTIES!
NULL NULL
NULL NULL NULL
NULL NULL NULL NULL
NULL NULL
NULL NULL NULL NULL
NULL
A Real World Tree
A General Tree
T1 T2 T3 T4
…… Tn
Sub Trees
❖ A tree structure means that the data are organized so that
items of information are related by branches.
node *rootPtr;
Tree Nodes Can Have Many Children
A tree node can have more than just two children:
struct node
{
int value; // node data
struct node
{
int value; // node data 3
node *pChildren[26]; NULL
};
7 4 15
NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL
Familiarity with Tree Terms
B,C,D,E,F and G are children of A
A is the root
G is parent of N
and child of A
M is child of F and
grandchild of A
A is an ancestor of P
P is a descendant of A
Degree of tree = 6 3
B C
D E F
G H
A A A A A
B B B C B C
D E F
LEVEL
A 0
Degree of Binary Tree <= 2
B C 1
D E F G 2
H I J K 3
L M N 4
Binary Trees
A binary tree is a special form of tree. In a binary tree,
every node has at most two children nodes:
A left child and a right child.
Each node in the tree has either no children or exactly two child nodes.
Example: A
B C Also known
as
D E Full Binary
Tree
F G
Complete Binary Trees
• A Complete Binary Tree is a binary tree in which every level, except
possibly the last, is completely filled, and all nodes are as far left as
possible.
Almost Complete
Binary Tree
B C 1
D E F G 2
H I J K L M N O 3
B C 1
D E F G 2
H I J K L M N O 3
Still…An
An almost Almost
NOTbinary
complete Complete
tree is not
An Almost Complete
always a full
Binary
binary tree
Tree
An Almost Binary
Complete TreeBinary Tree
A complete binary tree with n
vertices and height H satisfies:
• 2H ≤ n < 2H + 1
• H ≤ log n < H + 1
• H = floor(log n)
Skewed Binary Trees
A A
B B
C
C
D D
Level 0 D E
Level 1 Level 2
3 4 5 6
Example
[0] A
A
[1] B
0
[2] ---
B [3] C
1 [4] ---
Array Representation
C [5] ---
3 [6] ---
[7] D
D
[8] ---
7
#include<bits/stdc++.h>
using namespace std;
char tree[10];
int root(char key) {
if (tree[0] != '\0')
cout << "Tree already had root";
else
tree[0] = key;
return 0;
}
Array Implementation
int print_tree() {
cout << "\n";
for (int i = 0; i < 10; i++) {
if (tree[i] != '\0')
cout << tree[i];
else
cout << "-";
}
return 0;
}
Array Implementation
// Driver Code
int main() {
root('A');
set_left('B',0);
set_right('C', 0);
set_left('D', 1);
set_right('E', 1);
set_right('F', 2);
print_tree();
return 0;
}
Link List Representation of Binary Tree
❖ Here a single tree node consist of three fields such as,
❖ Data: It holds the value of the node
❖ Left child: It is a link field which contains the address of its left child
❖ Right child: It contains the address of its right child
struct treenode
Structure of the Node {
char data ;
struct treenode *lchild ;
struct treenode *rchild ;
};
A 0 Example The field value is
NULL when child
node is absent
B 1 C 2
NULL B NULL C
reserve 12 bytes
temp->left = NULL;
temp->right = NULL;
of memory
pRoot->left = temp;
temp-> for
value 7
1200
me? left right temp-> value -3 1100
temp = new BTNODE;
temp->value = -3; NULL NULL Sure, here’s a
left right
temp->left = NULL; chunk ofNULLmemory
NULL
temp->right = NULL; at address 1200.
1100.
1000.
pRoot->right = temp; And of course, later we’d have
// etc…
to delete our tree’s nodes.
Expression Trees
Expression Tree is a binary tree associated with an arithmetic expression,
here
• internal nodes are operators
• external nodes are operands
2 − 3 b
a 1
Maximum Depth of Binary Tree
Follow the steps below to solve the problem:
1. If the tree is empty then return 0.
2. Otherwise, do the following
• Get the max depth of the left subtree recursively i.e.
call maxDepth( node->left).
• Get the max depth of the right subtree recursively i.e.
call maxDepth( node->right).
• Get the max of max depths of left and right subtrees and add
1 to it for the current node.
• maxDepth = max(maxDepth of left subtree, max depth of right
subtree) + 1.
3. Return maxDepth.
Implementation
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* left; int maxDepth(struct Node* node) {
struct Node* right; }; if (node == NULL)
return 0;
Preorder Traversal
Inorder Traversal
Postorder Traversal
Recursive Traversal Algorithms
Preorder Traversal
Preorder(T)
Step 1: Process the root node (say R) → Visit
Step 2: Traverse the left subtree in Preorder
Step 3: Traverse the right subtree in Preorder
Example: A Preorder Sequence:
A B D E HC F G I
B C
D E F G
H I
The Pre-order Traversal cur a
“a” root
Output:
cur b
“b” “c”
NULL NULL
“d” e
“e” cur
NULL NULL NULL NULL
“d” “e”
NULL NULL NULL NULL
“d” “e”
NULL NULL NULL NULL
D E F G
H I
The In-order Traversal
1. Process the nodes in the left
sub-tree. cur “a” root
2. Process the current node.
3. Process the nodes in the right
sub-tree. cur “b” “c”
NULL NULL NULL NULL
D E F G
H I
The Post-order Traversal
1. Process the nodes in the left
sub-tree. cur “a” root
2. Process the nodes in the right
sub-tree.
3. Process the current node. cur “b” “c”
NULL NULL NULL NULL
D E F G
H I J
Preorder: A B D E H C F G I K J K
Inorder: D B H E A F C K I G J
Postorder: D H E B F K I J G C A
In Preorder Traversal Sequence:
The root is always present at the
beginning (followed by the left & then
the right subtree nodes)
Preorder:
A B D E H C F G I K J
Inorder:
D B H E A F C K I G J
Postorder:
D H E B F K I J G C A
Big-Oh of Traversals?
Question: What’re the big-ohs of each of our traversals?
O(n)
if (cur == NULL)
return;
cout << cur->value;
PostOrder(cur->left);
PostOrder(cur-> right);
}
An Easy Way to Remember the Order of
Pre/In/Post Traversals
2 7
Draw a dot next to each node as
3 4 8 you pass by its left side.
5 6 9
5 8
Draw a dot next to each node as
1 4 7 you pass by its right side.
2 3 6
The order you draw the dots is the
order of the post-order traversal!
Post-order:
ACEDBHIGF
Level-order Traversal: Level-by-level
To determine the order of nodes
1
visited in a level-order traversal…
2 3
Start at the top node and draw a
4 5 6
horizontal line left-to-right
7 8 9 through all nodes on that row.
1
/\
2 3
/
4
/
5
Question
50
/ \
25 75
/ \ / \
22 40 60 80
/\ /
15 30 90
Question
Inorder Traversal:
50
15, 22, 25, 30, 40, 50, 60, 75, 80, 90
/ \
Preorder Traversal:
25 75
50, 25, 22, 15, 30, 40, 75, 60, 80, 90
/ \ / \
Postorder Traversal:
22 40 60 80
15, 30, 22, 40, 25, 60, 90, 80, 75, 50
/\ /
Level Order Traversal:
15 30 90
50, 25, 75, 22, 40, 60, 80, 15, 30, 90
77
Practice Question
Construct a binary tree from its
inorder and preorder traversals
3
/\
9 20
/ \
15 7
Construct a binary tree from its inorder
and postorder traversals
Tree 1 Tree 2
A A
/\ / \
B C B C
/\ \ /\ /
D E F D E F
Expression Evaluation
We can represent arithmetic expressions using a
binary tree.
Expression Evaluation
Here’s our evaluation function. We start by passing in a
pointer to the root of the tree.
(5+6)*(3-1)
1. If the current node is a
1. If the current
number, returnnode is a
its value. ptr
number, return its value.
2. Recursively evaluate the left cur
2. RecursivelyResult
subtree and evaluate= 5the
get the left
result.
subtree and get the result.
3. Recursively evaluate the right
3. RecursivelyResult
subtree and evaluate= 6the
get the right
result. cur
subtree and get the result.
4. Apply the operator in the
4. Apply thenode
current operator
to thein left
the and
current node toreturn
right results; the lefttheand
right results; return the
result. 5+6 = 11
result.
Expression Evaluation
Here’s our evaluation function. We start by passing in a
pointer to the root of the tree.
(5+6)*(3-1)
1. If the current node is a
1. If the current
number, returnnode is a
its value. ptr
number, return its value.
2. Recursively evaluate the left cur
2. RecursivelyResult
evaluate
subtree Result
and = 3the
get=the left
result.
11
subtree and get the result.
3. Recursively evaluate the right
3. Recursively
subtree andResult
evaluate= 1the
get the right
result.
subtree and get the result.
4. Apply the operator in the
4. Apply thenode
current operator
to thein left
the and
current node toreturn
right results; the lefttheand
right results; return the
result. 3-1 = 2
result.
Expression Evaluation
Here’s our evaluation function. We start by passing in a
pointer to the root of the tree.
a) Deque
b) Priority Queue
c) Tree
d) All the above
Answer
c
Solve This
The depth of a complete binary tree with n nodes is
given by
a) D = n log n
b) D = log n +1
c) D = log n
d) D = n log n +1
Answer
b
Answer This
Which of the following is a pre-order traversal?
Answer
c
One More
If node N is a terminal node in a binary tree then its .........
Answer
d
Binary Search Tree
A binary tree T is termed as a Binary Search Tree(BST), if each node n
of T satisfies the following properties:
• The value at n is greater than every value on the left subtree of n,
and
• The value at n is less than or equal to every value on the right
subtree of n.
Left 30 70 Right
Subtree Subtree of 70
of 30
Left 20 40 60 80
Subtree Left
of 20 Right
10 Subtree of 30 Subtree of 70
Operations on a Binary Search Tree
Here’s what we can do to a BST:
Gary
Gary==
<== Larry??
> Fran??
Larry??
Fran??
Fran??
Gary?? “Fran” “Ronda”
NULL NULL
pRoot
14 == 13??
< 17??
13??
17??
14?? ptr-> 13
pRoot
ptr-> 13
true
bool Search(int V, Node *ptr)
7 ptr-> 17
{
boolif Search(int V, Node *ptr)
(ptr == NULL) NULL
true
{ return(false); // nope
if (ptr
else if ==
(V NULL)
== ptr->value)
3 14 19
return(false);
return(true); // // found!!!
nope NULL NULL NULL NULL NULL NULL
else
else if
if (V
(V == ptr->value)
< ptr->value)
return(true); true
// found!!!
return(Search(V,ptr->left));
void main(void)
else
else if (V < ptr->value)
return(Search(V,ptr->left));
return(Search(V,ptr->right)); {
} else bool bFnd;
return(Search(V,ptr->right)); bFnd = Search(14,pRoot);
} }
Recursive BST Search
Lets search for 14.
pRoot true
ptr-> 13
true
7 17
bool Search(int V, Node *ptr) NULL
true
{
if (ptr == NULL)
3 14 19
return(false); // nope NULL NULL NULL NULL NULL NULL
else if (V == ptr->value)
return(true); // found!!!
int main(void)
else if (V < ptr->value)
return(Search(V,ptr->left)); {
else bool bFnd;
true
return(Search(V,ptr->right)); true
bFnd = Search(14,pRoot);
} }
112
Right! N steps
Inserting A New Value Into A BST
To insert a new node in our BST, we must place the
new node so that the resulting tree is still a valid BST!
Alice Carly
Pseudo Code
Once we’ve found the right spot, we can insert our new
node in O(1) time.
Finding Min & Max of a BST
How do we find the minimum and maximum values in a BST?
The minimum value is located at the left-most node.
The maximum value is located at the right-most node.
return(pRoot->value); return(pRoot->value);
} }
return(GetMin(pRoot->left)); return(GetMax(pRoot->right));
} }
Printing a BST In Alphabetical Order
“bill” “frank”
cur NULL NULL NULL NULL cur
void InOrder(Node *cur)
{ Big-oh Alert!
if (cur == NULL) // if empty, return… Output:
return; the big-Oh of printing
So what’s
bill
all the items in the
InOrder(cur->left); tree?
// Process nodes in left sub-tree.
danny
cout << cur->value; // Process the current node. frank
Right! O(n) since we have to visit jane
InOrder(cur->right); // Process nodes in right sub-tree.
} and print all n items. waa
Freeing The Whole Tree
When we are done with our BST, we have to free every
node in the tree, one at a time.
cur-> “Gabby”
void FreeTree(Node *cur) NULL NULL
void
{ FreeTree(Node *cur)
{ FreeTree(Node
void if (cur == NULL)
*cur)
{ if (curreturn;
== NULL)
if (curreturn;
== NULL)
FreeTree(cur->left);
return;
FreeTree(cur->left);
FreeTree (cur-> right);
FreeTree(cur->left);
FreeTree (cur-> right);
delete(cur->
FreeTree cur; right);
delete
} cur;
}
delete cur;
}
Freeing The Whole Tree
cur-> “Larry”
parent
cur
Example- Case 1: Node is a leaf.
Example- Case 2: Node has one child
Example- Case 3: Node has two children.
in-order predecessor (largest value in the left sub-tree)
Note: Deleting a Node with Two Children To handle case 3, replace the
node’s value with its in-order predecessor (largest value in the left sub-tree)
or in-order successor (smallest value in the right sub-tree).
Example- Case 3: Node has two children.
in-order successor (smallest value in the right sub-tree)
Code
#include <stdio.h>
#include <stdlib.h>
c e i
igloo
infer
AVL
TREES
Balanced binary tree
✓ The disadvantage of a binary search tree is that its height can be as
large as N-1
✓ This means that the time needed to perform insertion and deletion
and many other operations can be O(N) in the worst case
✓ Such trees are called balanced binary search trees. Examples are
AVL tree, red-black tree.
Balanced Search Trees
Question:
What happens if we insert the following values into a
binary search tree?
Question:
What is the approximate big-oh cost of searching
for a value in this tree?
O(N)…
Balanced Search Trees
In real life, BSTs often
end up looking just like
our example, especially
after repeated insertions
and deletions.
J
Consider node T…
B T
R Z
3
3
Its left
And its right
subtree
has a subtree has a
height height of 3 too…
of 3…
Balancing a Tree On Insertion
For example, the AVL Tree tracks the height of ALL subtrees in the BST.
Or consider
node J… The AVL tree tracks these
subtree height values for every
J node in the tree!
B T
3
Its left
subtree has a
height of 3…
Balancing a Tree On Insertion
For example, the AVL Tree tracks the height of ALL subtrees in the BST.
4
45
3
5 13
8
5 20
13
18 3 8 18 22
20
22
Motivation
❖ Complete binary tree is hard to build when we allow
dynamic insert and remove.
➢ We want a tree that has the following properties
✓ Tree height = O(log(N))
✓ allows dynamic insert and remove with O(log(N)) time
complexity.
▪ The AVL tree is one of this kind of trees.
8
13
5 18
5 20
3 13 20
3 8 18 22 22
AVL (Adelson-Velskii and Landis) Trees
4
44
• An AVL Tree is a binary 2 3
search tree such that for 17 78
every internal node v of T, 1 2 1
the heights of the children 32 50 88
of v can differ by at most 1. 1 1
48 62
Tree A Tree B
(AVL) (AVL)
height=2 BF=1-0=1 2
6 6
1 0 1 1
4 9 4 9
0 0 0 0 0
1 5 1 5 8
height of node = h
balance factor = hleft-hright
empty height = -1
Node Heights after Insert 7
1 5 8 1 4 6 9
AVL Trees 157
AVL - Good but not Perfect
Balance
• AVL trees are height-balanced binary
search trees
• Balance factor of a node
› height(left subtree) - height(right subtree)
• An AVL tree has balance factor
calculated at every node
› For every node, heights of left and right
subtree can differ by no more than 1
› Store current heights in each node
AVL Trees 158
Insert and Rotation in AVL
Trees
• Insert operation may cause balance factor
to become 2 or –2 for some node
› only nodes on the path from insertion point to
root node have possibly changed in height
› So after the Insert, go back up to the root
node by node, updating heights
› If a new balance factor (the difference hleft-
hright) is 2 or –2, adjust tree by rotation around
the node
AVL Trees 159
Rotation in an AVL Tree
-LL rotation: The new node is inserted in the left sub-
tree of the left sub-tree of the critical node.
-RR rotation: The new node is inserted in the right
sub-tree of the right sub-tree of the critical node.
-LR rotation: The new node is inserted in the right
sub-tree of the left sub-tree of the critical node.
-RL rotation: The new node is inserted in the left sub-
tree of the right sub-tree of the critical node.
Single Rotation in an AVL
Tree
2 2
6 6
1 2 1 1
4 9 4 8
0 0 1 0 0 0 0
1 5 8 1 5 7 9
0
7
k h
h
h
Z
X Y
AVL Trees 163
AVL Insertion: Outside Case
j Inserting into X
destroys the AVL
property at node j
k h
h+1 h Z
Y
X
AVL Trees 164
AVL Insertion: Outside Case
j Do a “right rotation”
k h
h+1 h Z
Y
X
AVL Trees 165
Single right rotation
j Do a “right rotation”
k h
h+1 h Z
Y
X
AVL Trees 166
Outside Case Completed
“Right rotation” done!
k (“Left rotation” is mirror
symmetric)
h+1
j
h h
X Y Z
AVL property has been restored!
AVL Trees 167
AVL Insertion: Inside Case
Consider a valid
AVL subtree
j
k h
h h Z
X Y
AVL Trees 168
AVL Insertion: Inside Case
Inserting into Y
destroys the j Does “right rotation”
restore balance?
AVL property
at node j
k h
h h+1 Z
X
Y
AVL Trees 169
AVL Insertion: Inside Case
“Right rotation”
k does not restore
balance… now k is
h j out of balance
X h+1
h
Z
Y
AVL Trees 170
AVL Insertion: Inside Case
Consider the structure
of subtree Y… j
k h
h h+1 Z
X
Y
AVL Trees 171
AVL Insertion: Inside Case
Y = node i and
subtrees V and W
j
k h
h
i h+1 Z
X h or h-1
V W
AVL Trees 172
AVL Insertion: Inside Case
j We will do a left-right
“double rotation” . . .
k
i Z
X
V W
AVL Trees 173
Double rotation : first rotation
j left rotation complete
i
k Z
W
X V
AVL Trees 174
Double rotation : second
rotation
j Now do a right rotation
i
k Z
W
X V
AVL Trees 175
Double rotation : second
rotation
right rotation complete
k j
h h
h or h-1
X V W Z
AVL Trees 176
Implementation
balance (1,0,-1)
key
left right
0 45
Now Insert 34
14
11 17
7 53
4
AVL Tree Example:
• Insert 14, 17, 11, 7, 53, 4, 13 into an empty AVL tree
14
7 17
4 11 53
13
AVL Tree Example:
• Now insert 12
14
7 17
4 11 53
13
12
AVL Tree Example:
• Now insert 12
14
7 17
4 11 53
12
13
AVL Tree Example:
• Now the AVL tree is balanced.
14
7 17
4 12 53
11 13
AVL Tree Example:
• Now insert 8
14
7 17
4 12 53
11 13
8
AVL Tree Example:
• Now insert 8
14
7 17
4 11 53
8 12
13
AVL Tree Example:
• Now the AVL tree is balanced.
14
11 17
7 12 53
4 8 13
AVL Tree Example:
• Now remove 53
14
11 17
7 12 53
4 8 13
AVL Tree Example:
• Now remove 53, unbalanced
14
11 17
7 12
4 8 13
AVL Tree Example:
• Balanced! Remove 11
11
7 14
4 8 12 17
13
AVL Tree Example:
• Remove 11, replace it with the largest in its left branch
8
7 14
4 12 17
13
AVL Tree Example:
• Remove 8, unbalanced
7
4 14
12 17
13
AVL Tree Example:
• Remove 8, unbalanced
7
4 12
14
13 17
AVL Tree Example:
• Balanced!!
12
7 14
4 13 17
Exercises
• Build an AVL tree with the following values:
15, 20, 24, 10, 13, 7, 30, 36, 25
15, 20, 24, 10, 13, 7, 30, 36, 25
20
15
15 24
20
10
24
13
20 20
13 24 15 24
10 15 13
10
15, 20, 24, 10, 13, 7, 30, 36, 25
20
13
13 24 10 20
10 15 7 15 24
7 30
13 36
10 20
7 15 30
24 36
15, 20, 24, 10, 13, 7, 30, 36, 25
13 13
10 20 10 20
7 15 30 7 15 24
24 36 30
25 13 25 36
10 24
7 20 30
15 25 36
Remove 24 and 20 from the AVL tree.
13 13
10 24 10 20
7 20 30 7 15 30
15 25 36 25 36
13 13
10 30 10 15
7 15 36 7 30
25 25 36
Extended Example
Insert 3,2,1,4,5,6,7, 16,15,14
3 2
3
3
2 1
Fig 1 2 3
Fig 4
Fig 2
2 1 2
Fig 3
1
1 3
3
Fig 5 Fig 6 4
4
5
2
2
1
1
4 4
3 5
3 5
Fig 8
Fig 7 6
4
4
2
2 5
5
1 3 6
1 3 6
4
Fig 10 7
Fig 9
2
6
1 3 7
5 Fig 11
4 4
2 2
6 6
1 3 7 1 3 7
5 16 5 16
Fig 12
Fig 13
15
4
2
6
1 3 15
5
16
Fig 14 7
4 4
2 2 7
6
15 1 3 15
1 3 5 6
16
7 5 14 16
Fig 15
14 Fig 16
Any Questions???