Professional Documents
Culture Documents
Tree
Tree
Tree
2
Tree
Definition (recursively): A tree is a finite set of one
or more nodes such that
There is a specially designated node called root.
The remaining nodes are partitioned into n>=0 disjoint set
T1,…,Tn, where each of these sets is a tree. T1,…,Tn are called
the subtrees of the root.
Every node in the tree is the root of some subtree
Tree
5/4/2022 CS 201
Tree:-Properties
•The important properties of tree data structure are-
•There is one and only one path between every pair of vertices
in a tree.
5
Tree Terminology-
The important terms related to tree data structure are-
6
Tree:-Root
•The first node from where the tree originates is called as
a root node.
• In any tree, there must be only one root node.
•We can never have multiple root nodes in a tree data
structure.
Example
7
Tree:- Edge
•The connecting link between any two nodes is called as
an edge.
• In a tree with n number of nodes, there are exactly (n-1)
number of edges.
Example
8
Tree:- Parent
•The node which has a branch from it to any other node is
called as a parent node.
• In other words, the node which has one or more children is
called as a parent node.
• In a tree, a parent node can have any number of child nodes.
Example
9
Tree:- Parent
Here,
10
Tree:- Child
•The node which is a descendant of some node is called as
a child node.
•All the nodes except root node are child nodes.
Example
11
Tree:- Child
Here,
12
Tree:- Siblings
•Nodes which belong to the same parent are called as siblings.
•In other words, nodes with the same parent are sibling nodes.
Example
13
Tree:- Sibling
Here,
14
Tree:- Degree
•Degree of a node is the total number of children of that node.
•Degree of a tree is the highest degree of a node among all the
nodes in the tree.
Example
15
Tree:- Degree
Here,
•Degree of node A = 2
•Degree of node B = 3
•Degree of node C = 2
•Degree of node D = 0
•Degree of node E = 2
•Degree of node F = 0
•Degree of node G = 1
•Degree of node H = 0
•Degree of node I = 0
•Degree of node J = 0
•Degree of node K = 0
16
Tree:- Internal Node
•The node which has at least one child is called as an internal
node.
•Internal nodes are also called as non-terminal nodes.
•Every non-leaf node is an internal node.
Example
Example
Example
19
Tree:- Height
•Total number of edges that lies on the longest path from any
leaf node to a particular node is called as height of that node.
• Height of a tree is the height of root node.
•Height of all leaf nodes = 0
Example
20
Tree:- Height
Here, •Height of node A = 3
•Height of node B = 2
•Height of node C = 2
•Height of node D = 0
•Height of node E = 1
•Height of node F = 0
•Height of node G = 1
•Height of node H = 0
•Height of node I = 0
•Height of node J = 0
•Height of node K = 0
21
Tree:- Depth
•Total number of edges from root node to a particular node is
called as depth of that node.
•Depth of a tree is the total number of edges from root node to
a leaf node in the longest path.
Example
22
Tree:- Depth
•Depth of the root node = 0
•The terms “level” and “depth” are used interchangeably.
Here
• Depth of node A = 0
•Depth of node B = 1
•Depth of node C = 1
•Depth of node D = 2
•Depth of node E = 2
•Depth of node F = 2
•Depth of node G = 2
•Depth of node H = 2
•Depth of node I = 3
•Depth of node J = 3
•Depth of node K = 3
23
Tree:- Subtree
•In a tree, each child from a node forms a subtree recursively.
•Every child node forms a subtree on its parent node.
Example
24
Tree:- Forest
•A forest is a set of disjoint trees.
Example
25
Binary Tree
Binary Tree is a rooted tree in which
root can have maximum two children
such that each of them is again a binary
tree. That means, there can be 0,1, or 2
children of any node.
Binary Tree
Binary Trees
The abstract data type of binary tree
Strict Binary Tree
Strict Binary Tree is a Binary tree in
which root can have exactly two
children or no children at all. That
means, there can be 0 or 2 children of
any node.
Strict Binary Tree
Binary Trees
Two special kinds of binary trees:
(a) skewed tree, (b) complete binary tree
The all leaf nodes of these trees are on two adjacent levels
Binary Trees
Properties of binary trees
Lemma 5.1 [Maximum number of nodes]:
1. The maximum number of nodes on level i of a binary tree
is 2i-1, i 1.
2. The maximum number of nodes in a binary tree of depth k
is 2k-1, k1.
Lemma 5.2 [Relation between number of leaf nodes and
degree-2 nodes]:
For any nonempty binary tree, T, if n0 is the number of leaf
nodes and n2 is the number of nodes of degree 2, then n0
= n2 + 1.
These lemmas allow us to define full and complete
binary trees
Binary Trees
Definition:
A full binary tree of depth k is a binary tree of death k having 2k-1
nodes, k 0.
A binary tree with n nodes and depth k is complete iff its nodes
correspond to the nodes numbered from 1 to n in the full binary
tree of depth k.
From Lemma 5.1, the
height of a complete
binary tree with n nodes
is log2(n+1)
Complete Binary Tree
Complete Binary Tree is a Strict Binary
tree in which every leaf node is at same
level. That means, there are equal
number of children in right and left
subtree for every node.
Complete Binary Tree
Extended Binary Tree
⚫ A binary tree with special nodes replacing every null
subtree. Every regular node has two children, and
every special node has no children.
Extended Binary Tree
⚫ An extended binary tree is a transformation of
any binary tree into a complete binary tree.
Binary Trees 38
Binary Trees
Binary tree representations (using array)
Lemma 5.3: If a complete binary tree with n nodes is
represented sequentially, then for any node with index i,
1 i n, we have
1. parent(i) is at i /2 if i 1.
If i = 1, i is at the root and has no parent.
2. LeftChild(i) is at 2i if 2i n.
If 2i n, then i has no left child.
3. RightChild(i) is at 2i+1 if 2i+1 n.
A 1
If 2i +1 n, then i has no left child
2 3
b c
4 5 6 7
d e f g
8 9 10
h i j
tree[] a b c d e f g h i j
0 5 10
Binary Trees
Binary tree representations (using array)
Waste spaces: in the worst case, a skewed tree of depth k
requires 2k-1 spaces. Of these, only k spaces will be occupied
Insertion or deletion
of nodes from the
middle of a tree
requires the
movement of
potentially many nodes
to reflect the change in
the level of these nodes
Right-Skewed Binary Tree
a1
b 3
7
c
15
d
tree[] a - b - - - c - - - - - - - d
0 5 10 15
b c
d e
g
f
leftChild
h
rightChild
Binary Trees
Binary tree representations (using link)
Binary Trees
Binary tree representations (using link)
Binary Tree Traversals
How to traverse a tree or visit each node in the tree
exactly once?
There are six possible combinations of traversal
LVR, LRV, VLR, VRL, RVL, RLV
Adopt convention that we traverse left before
right, only 3 traversals remain
LVR (inorder), LRV (postorder), VLR (preorder)
output: A / B * C * D + E
ptr
L
V
R
Binary Tree Traversals (4/9)
Preorder traversal (VLR) (recursive version)
output: + * * / A B C D E
V
L
R
Binary Tree Traversals (5/9)
Postorder traversal (LRV) (recursive version)
output: A B / C * D * E +
L
R
V
Binary Tree Traversals (6/9)
Iterative inorder traversal
we use a stack to simulate recursion
5 4 11
8 3 14
2 17
1
A B
/ *C * E+
D
L
V
output: A /B *C *D + E node
Binary Tree Traversals
Analysis of inorder2 (Non-recursive Inorder traversal)
Let n be the number of nodes in the tree
Time complexity: O(n)
Every node of the tree is placed on and removed
from the stack exactly once
Space complexity: O(n)
equal to the depth of the tree which
(skewed tree is the worst case)
Binary Tree Traversals
Level-order traversal
method:
We visit the root first, then the root’s left child, followed by the root’s
right child.
We continue in this manner, visiting the nodes at each new level from
the leftmost node to the rightmost nodes
This traversal requires a queue to implement
Binary Tree Traversals
Level-order traversal (using queue)
output: + * E * D / C A B
1 17 3 14 4 11 5
2 8
*+ E * D / C A B
FIFO
ptr
Additional Binary Tree Operations
node structure
For the purpose of our evaluation algorithm, we assume each
node has four fields:
⚫ Right part -
Constructing Binary Tree
Constructing Binary Tree
Constructing Binary Tree
Constructing Binary Tree
Constructing Binary Tree
Constructing Binary Tree
Constructing Binary Tree
Constructing Binary Tree
Constructing Binary Tree
Constructing Binary Tree
Constructing Binary Tree
Constructing Binary Tree
Constructing Binary Tree
Threaded Binary Trees
Threads
Do you find any drawback of the above tree?
Too many null pointers in current representation of binary
trees
n: number of nodes
number of non-null links: n-1
total links: 2n
null links: 2n-(n-1) = n+1
Solution: replace these null pointers with some useful
“threads”
Threaded Binary Trees
Threads
Threads; Threading Consider again the linked representation
of a binary tree T. Approximately half of the entries in the
pointer fields LEFT and RIGHT will contain null elements.
This space may be more efficiently used by replacing the null
entries by some other type of information.
root A
t: true thread
f: false child
dangling
f B f C
D t E t F G
dangling
inorder traversal:
H I
H D I B E A F C G
Threaded Binary
Trees
Two additional fields of the node structure,
left-thread and right-thread
If ptr->left-thread=TRUE,
then ptr->left-child contains a thread;
Otherwise it contains a pointer to the left child.
Similarly for the right-thread
Threaded Binary Trees
If we don’t want the left pointer of H and the right
pointer of G to be dangling pointers, we may create
root node and assign them pointing to the root node
Threaded Binary Trees
Inorder traversal of a threaded binary tree
By using of threads we can perform an inorder traversal
without making use of a stack (simplifying the task)
Now, we can follow the thread of any node, ptr, to the “next”
node of inorder traversal
1. If ptr->right_thread = TRUE, the inorder successor of ptr is
ptr->right_child by definition of the threads
2. Otherwise we obtain the inorder successor of ptr by
following a path of left-child links from the right-child of
ptr until we reach a node with left_thread = TRUE
Threaded Binary Trees
Finding the inorder successor (next node) of a node
threaded_pointer insucc(threaded_pointer tree){
threaded_pointer temp;
temp = tree->right_child;
if (!tree->right_thread) tree
while (!temp->left_thread)
temp = temp->left_child;
return temp;
}
temp
Inorder
Threaded Binary Trees
Inorder traversal of a threaded binary tree
void tinorder(threaded_pointer tree){
/* traverse the threaded binary tree inorder */
threaded_pointer temp = tree;
for (;;) { output: H D I B E A F C G
temp = insucc(temp);
if (temp==tree)
break;
printf(“%3c”,temp->data); tree
}
}
O(h)
Binary Search Tree
The value at any node,
• Greater than every value in left subtree
• Smaller than every value in right subtree
– Example
• Y>X
• Y<Z Y
X Z
Binary Search Tree
• Values in left sub tree less than parent
• Values in right sub tree greater than parent
• Fast searches in a Binary Search tree, maximum of log
n comparisons
31
21 40
10 22 35 42
Binary Search Trees
• Examples 5
10 10
2 45
5 30 5 45
30
2 25 45 2 25 30
10
25
Binary search Not a binary
trees search tree
Example Binary Searches
• search (root, 25 )
10 5
10 < 25, right 5 < 25, right
5 30 30 > 25, left 2 45 45 > 25, left
25 = 25, found 30 > 25, left
2 25 45 30
10 < 25, right
10 25 = 25, found
25
Algorithm for Binary Search Tree
⚫ A) compare ITEM with the root node N of the tree
⚫ i) if ITEM<N, proceed to the left child of N.
⚫ ii) if ITEM>N, proceed to the right child of N.
⚫ B) repeat step (A) until one of the following occurs
⚫ i) we meet a node N such that ITEM=N, i.e. search is
successful.
⚫ ii) we meet an empty sub tree, i.e. the search is
unsuccessful.
Binary Tree Implementation
typedef struct node
{
int data;
struct node *lc,*rc;
};
Iterative Search of Binary Search Tree
search()
{
while (n != NULL)
{
if (n->data == item) // Found it
return n;
if (n->data > item) // In left subtree
n = n->lc;
else // In right subtree
n = n->rc;
}
return null;
}
Recursive Search of Binary Search Tree
Search(node *n, info)
{
if (n == NULL) // Not found
return( n );
else if (n->data == item) // Found it
return( n );
else if (n->data > item) // In left subtree
return search( n->left, item );
else // In right subtree
return search( n->right, item );
}
Binary Search Trees
Inserting into a binary search tree
An empty tree
Insertion in a Binary Search Tree
• Algorithm
1. Perform search for value X
2. Search will end at node Y (if X not in tree)
3. If X < Y, insert new leaf X as new left subtree
for Y
4. If X > Y, insert new leaf X as new right subtree
for Y
Insertion in a Binary Search Tree
• Insert ( 20 )
10 10 < 20, right
30 > 20, left
5 30
25 > 20, left
2 25 45 Insert 20 on left
20
Insertion in a Binary Tree
40, 60, 50, 33, 55, 11
40
Insertion in a Binary Tree
40, 60, 50, 33, 55, 11
40
60
Insertion in a Binary Tree
40, 60, 50, 33, 55, 11
40
60
50
Insertion in a Binary Tree
40, 60, 50, 33, 55, 11
40
33 60
50
Insertion in a Binary Tree
40, 60, 50, 33, 55, 11
40
33 60
50
55
Insertion in a Binary Tree
40, 60, 50, 33, 55, 11
40
33 60
11 50
55
Deletion in Binary Tree
• Algorithm
1. Perform search for value X
2. If X is a leaf, delete X
3. Else //we must delete internal node
a) Replace with largest value Y on left subtree
OR smallest value Z on right subtree
b) Delete replacement value (Y or Z) from subtree
Note :-
– Deletions may unbalance tree
Example Deletion (Leaf)
• Delete ( 25 )
10 10
10 < 25, right
5 30 30 > 25, left 5 30
25 = 25, delete
2 25 45 2 45
Example Deletion (Internal Node)
• Delete ( 10 )
10 5 5
5 30 5 30 2 30
2 25 45 2 25 45 2 25 45
• Delete ( 10 )
10 25 25
5 30 5 30 5 30
2 25 45 2 25 45 2 45
0 0 0
0
AVL Tree
1
-1 0
3 2
0 1 0 0
Balanced as LST-RST=1
Insertion in AVL Tree
2
3
Case 3: the node was heavy and the new node has been inserted in
the heavy sub tree thus creating an unbalanced sub tree
Rebalancing
• When the tree structure changes (e.g., insertion or
deletion), we need to transform the tree to restore the
AVL tree property.
• This is done using single rotations or double rotations.
Rotations
• single rotations
3
Example
Insert 3,2,1,4,5,6,7
3
2
Example
Insert 3,2,1,4,5,6,7
3
1
Example
Insert 3,2,1,4,5,6,7
Single rotation
1
Example
Insert 3,2,1,4,5,6,7
2
1
3
Example
Insert 3,2,1,4,5,6,7
2
1
3
4
Example
Insert 3,2,1,4,5,6,7
2
1
3
5
Example
Insert 3,2,1,4,5,6,7
2
Single rotation
1
3
5
Example
Insert 3,2,1,4,5,6,7
2
1
4
3 5
Example
Insert 3,2,1,4,5,6,7
2
1
4
3 5
6
Example
Insert 3,2,1,4,5,6,7
Single rotation
2
1
4
3 5
6
Example
Insert 3,2,1,4,5,6,7
4
2
5
1 3 6
Example
Insert 3,2,1,4,5,6,7
4
2
5
1 3 6
7
Example
Insert 3,2,1,4,5,6,7
4
Single rotation
2
5
1 3 6
7
Example
Insert 3,2,1,4,5,6,7
4
2
6
1 3 5 7
AVL Insertion: Outside Case
Consider a valid
AVL subtree
j
k h
h
h
Z
X Y
AVL Insertion: Outside Case
j Inserting into X
destroys the AVL
property at node j
k h
h+1 h Z
Y
X
AVL Insertion: Outside Case
j Do a “right rotation”
k h
h+1 h Z
Y
X
Single right rotation
j Do a “right rotation”
k h
h+1 h Z
Y
X
Outside Case Completed
h+1
j
h h
X Y Z
AVL property has been restored!
AVL Insertion: Inside Case
Consider a valid
AVL subtree
j
k h
h h Z
X Y
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 Insertion: Inside Case
k “Right rotation”
does not restore
balance… now k is
h j out of balance
X h+1
h
Z
Y
AVL Insertion: Inside Case
h h+1 Z
X
Y
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 Insertion: Inside Case
j We will do a left-right
“double rotation” . . .
k
i Z
X
V W
Double rotation : first rotation
i
k Z
W
X V
Double rotation : second rotation
i
k Z
W
X V
Double rotation : second rotation
k j
h h
h or h-1
X V W Z
Comparative analysis of AVL ,Red black, and
Splay Tree
Performance of Binary Search Tree (BST) is proportional to
its height O(h).
AVL tree, Red-Black tree and Splash tree are popular self-
balacing BSTs.
Like AVL tree, Splay tree and Red-Black tree are self-
balancing trees which provide O(Log n) search
performance.
Comparative analysis of AVL ,Red black, and
Splay Tree
•The AVL tree is another structure supporting O(log n) search, insertion, and
removal.
•It is more rigidly balanced than red–black trees, leading to slower insertion
and removal but faster retrieval.
•This makes it attractive for data structures that may be built once and loaded
without reconstruction, such as language dictionaries.
• The competitor of avl tree is Red–black tree. The worst case height of avl tree
is ~1.44 log(n), of red black tree is 2 log(n).
• But as insertion and deletion in avl tree is costly(more rotation than red
black tree) than red black,avl tree is not used much.
performance.
Comparative analysis of AVL ,Red black, and
Splay Tree
•Red-Black tree is preferred over AVL trees when there is
high frequency of insert/delete operations compared to
search as AVL tree balancing (rotation) is expensive.
•Red-black tree balances itself on insert and delete
operations satisfying the following conditions.
•Each node is either red or black. Usually color information
is stored in a bit in the node.
a) Root and leaf nodes are black.
b) No two red nodes to be adjacent, meaning, a red node
cannot have a parent or children which are red.
c) Every path from root to leaf nodes have same number of
black nodes.
Comparative analysis of AVL ,Red black, and
Splay Tree
•Splay tree provides performance better than O(log n)
by optimizing the placement of nodes.
C N G A H E K Q M F W L T Z D P R X Y S
H E K Q M F W LT Z D P R XY S
Inserting M requires a split. Note that M happens to be the
median key and so is moved up into the parent node.
M F W LT Z D P R XY S
When Z is added, the rightmost leaf must be split. The median item T is moved
up into the parent node. Note that by moving up the median key, the tree is kept
fairly balanced, with 2 keys in each of the resulting nodes.
The insertion of D causes the leftmost leaf to be split. D happens to be the median
key and so is the one moved up into the parent node. The letters P, R, X, and Y are
then added without any need of splitting:
Z D P R XY S
Finally, when S is added, the node with N, P, Q, and R splits, sending the
median Q up to the parent. However, the parent node is full, so it splits,
sending the median M up to form a new root node. Note how the 3
pointers from the old parent node stay in the revised node that contains D
and G.
THANK YOU