0% found this document useful (0 votes)
72 views103 pages

Trees

A tree is a hierarchical data structure where data is organized in a parent-child relationship. Key properties of trees include having a single root node, exactly one path between any two nodes, and (n-1) edges for a tree with n nodes. Common tree terminology includes root, edge, parent, child, siblings, internal/leaf nodes, height, depth, and subtree. Binary trees restrict each node to having at most two children. Different types of binary trees include rooted, full, complete, almost complete, and skewed binary trees. Tree traversal algorithms like preorder, inorder, and postorder visit each node exactly once.

Uploaded by

bulla
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
72 views103 pages

Trees

A tree is a hierarchical data structure where data is organized in a parent-child relationship. Key properties of trees include having a single root node, exactly one path between any two nodes, and (n-1) edges for a tree with n nodes. Common tree terminology includes root, edge, parent, child, siblings, internal/leaf nodes, height, depth, and subtree. Binary trees restrict each node to having at most two children. Different types of binary trees include rooted, full, complete, almost complete, and skewed binary trees. Tree traversal algorithms like preorder, inorder, and postorder visit each node exactly once.

Uploaded by

bulla
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 103

Trees

Definition

– Tree is a non-linear data structure which organizes data in


a hierarchical structure and this is a recursive definition.
OR

– A tree is a connected graph without any circuits.


OR

– If in a graph, there is one and only one path between every


pair of vertices, then graph is called as a 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.
• A tree with n vertices has exactly (n-1) edges.
• A graph is a tree if and only if it is minimally connected.
• Any connected graph with n vertices and (n-1) edges is a
tree.
Tree Terminology-

1. 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.
2. 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.
3. 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 Here,
•Node A is the parent of nodes B and C
number of child nodes. •Node B is the parent of nodes D, E and F
•Node C is the parent of nodes G and H
•Node E is the parent of nodes I and J
•Node G is the parent of node K
4. Child
• The node which is a descendant of
some node is called as a child node.
• All the nodes except root node are
Here,
child nodes. •Nodes B and C are the children of node A
•Nodes D, E and F are the children of node B
•Nodes G and H are the children of node C
•Nodes I and J are the children of node E
•Node K is the child of node G
5. Siblings
• Nodes which belong to the same
parent are called as siblings.
• In other words, nodes with the same
parent are sibling nodes.

•Nodes B and C are siblings


•Nodes D, E and F are siblings
•Nodes G and H are siblings
•Nodes I and J are siblings
6. Degree
• Degree of a node is the total number
Here,
of children of that node. •Degree of node A = 2
•Degree of node B = 3
• Degree of a tree is the highest degree •Degree of node C = 2
of a node among all the nodes in the •Degree of node D = 0
tree. •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
7. Internal nodes
• The node which has at least one child
is called as an internal node.
• Internal nodes are also called as non- Here, nodes A, B, C, E and G are internal nodes.
terminal nodes.
• Every non-leaf node is an internal node.
8. Leaf node
• The node which does not have any
child is called as a leaf node.
• Leaf nodes are also called as external
nodes or terminal nodes.
Here, nodes D, I, J, F, K and H are leaf nodes.
9. Level
• In a tree, each step from top to
bottom is called as level of a tree.
• The level count starts with 0 and
increments by 1 at each level or step.
10. Height
• Total number of edges that lies on the
longest path from any leaf node to a Here,
•Height of node A = 3
particular node is called as height of •Height of node B = 2
that node. •Height of node C = 2
• Height of a tree is the height of root •Height of node D = 0
•Height of node E = 1
node. •Height of node F = 0
• Height of all leaf nodes = 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
11. Depth
• Total number of edges from root node to a
particular node is called as depth of that node. Here,
• Depth of a tree is the total number of edges •Depth of node A = 0
from root node to a leaf node in the longest •Depth of node B = 1
path. •Depth of node C = 1
•Depth of node D = 2
• Depth of the root node = 0 •Depth of node E = 2
• The terms “level” and “depth” are used •Depth of node F = 2
interchangeably. •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
12. Subtree
• In a tree, each child from a node
forms a subtree recursively.
• Every child node forms a subtree
on its parent node.
13. Forest
A forest is a set of disjoint trees.
Binary Tree

– Binary tree is a special tree data


structure in which each node can
have at most 2 children.
– Thus, in a binary tree, each node
has either 0 child or 1 child or 2
children.
Unlabeled Binary Tree

– A binary tree is unlabeled if its nodes


are not assigned any label.

Consider we want to draw all the binary trees possible with


3 unlabeled nodes.
Using the above formula, we have-

Number of binary trees possible with 3 unlabeled nodes


= 2 x 3C3 / (3 + 1)
= 6C3 / 4
=5
Labeled Binary Tree-

– A binary tree is labeled if all its nodes


are assigned a label.
Consider we want to draw all the binary trees possible with
3 labeled nodes.
Using the above formula, we have-

Number of binary trees possible with 3 labeled nodes


= { 2 x 3C3 / (3 + 1) } x 3!
= { 6C3 / 4 } x 6
=5x6
= 30
Types of Binary Trees

– Binary trees can be of the following


types-
1.Rooted Binary Tree
2.Full / Strictly Binary Tree
3.Complete / Perfect Binary Tree
4.Almost Complete Binary Tree
5.Skewed Binary Tree
Rooted Binary Tree

– A rooted binary tree is a binary tree


that satisfies the following 2
properties-
• It has a root node.
• Each node has at most 2 children.
Full / Strictly Binary Tree

• A binary tree in which every node has


either 0 or 2 children is called as a Full
binary tree.
• Full binary tree is also called as
Strictly binary tree.
Here,
•First binary tree is not a full binary tree.
•This is because node C has only 1 child.
Complete / Perfect Binary Tree-

– A complete binary tree is a binary tree


that satisfies the following 2 properties-
• Every internal node has exactly 2 children.
• All the leaf nodes are at the same level.
– Complete binary tree is also called as Here,
Perfect binary tree. •First binary tree is not a complete binary tree.
•This is because all the leaf nodes are not at the
same level.
Almost Complete Binary Tree-

– An almost complete binary tree is a


binary tree that satisfies the following
2 properties-
• All the levels are completely filled
except possibly the last level.
• The last level must be strictly filled
from left to right. Here,
•First binary tree is not an almost complete binary
tree.
•This is because the last level is not filled from left
to right.
Skewed Binary Tree-

– A skewed binary tree is a binary tree that


satisfies the following 2 properties-
• All the nodes except one node has one
and only one child.
• The remaining node has no child.
OR
– A skewed binary tree is a binary tree of n
nodes such that its depth is (n-1).
Tree Traversal-

– Tree Traversal refers to the process of


visiting each node in a tree data
structure exactly once.
Depth First Traversal-

– Following three traversal


techniques fall under Depth First
Traversal-
1.Preorder Traversal
2.Inorder Traversal
3.Postorder Traversal
1. Preorder Traversal-
Algorithm-

1. Visit the root


2. Traverse the left sub tree i.e. call Preorder
(left sub tree)
3. Traverse the right sub tree i.e. call Preorder
(right sub tree)

– Root → Left → Right


Pre-order Example
Pre-order
Pseudocode
struct Node{
char data;
Node *left;
Node *right;
}
void Preorder(Node *root)
{
if (root==NULL) return;
printf (“%c”, root->data);
Preorder(root->left);
Preorder(root->right);
}
2. Inorder Traversal-

Algorithm-

1.Traverse the left sub tree i.e. call Inorder


(left sub tree)
2.Visit the root
3.Traverse the right sub tree i.e. call Inorder
(right sub tree)

– Left → Root → Right


In-Order Example
In-order Pseudocode
struct Node{
char data;
Node *left;
Node *right;
}
void Inorder(Node *root)
{
if (root==NULL) return;
Inorder(root->left);
printf (“%c”, root->data);
Inorder(root->right);
}
3. Postorder Traversal-
Algorithm-

1. Traverse the left sub tree i.e. call Postorder


(left sub tree)
2. Traverse the right sub tree i.e. call
Postorder (right sub tree)
3. Visit the root

– Left → Right → Root


Post-Order Example
Post-order Pseudocode
struct Node{
char data;
Node *left;
Node *right;
}
void Postorder(Node *root)
{
if (root==NULL) return;
Postorder(root->left);
Postorder(root->right);
printf (“%c”, root->data);
}
Breadth First Traversal-

• Breadth First Traversal of a tree


prints all the nodes of a tree level by
level.
• Breadth First Traversal is also called
as Level Order Traversal.
Practice problems based
on tree traversal-
– If the binary tree in figure is
traversed in inorder, then the order
in which the nodes will be visited is
____?
– Which of the following sequences
denotes the postorder traversal
sequence of the tree shown in figure?
1.FEGCBDBA
2.GCBDAFE Postorder Traversal : G , C , D , B , F , E , A

3.GCDBFEA
4.FDEGCBA
– Which of the following binary trees
has its inorder and preorder
traversals as BCAD and ABCD
respectively-

Option (D) is correct.


Binary Tree Properties

– Minimum number of nodes in a binary tree of


height H = H + 1

– To construct a binary tree of height =


4, we need at least 4 + 1 = 5 nodes.
– Maximum number of nodes in a binary tree of
height H= 2H+1 – 1

– Maximum number of nodes in a


binary tree of height 3
= 23+1 – 1
= 16 – 1
= 15 nodes
Total Number of leaf nodes in a Binary Tree
= Total Number of nodes with 2 children + 1

Here,
•Number of leaf nodes = 3
•Number of nodes with 2 children = 2
•Clearly, number of leaf nodes is one greater than numbe
of nodes with 2 children.
– Maximum number of nodes at any level ‘L’ in a
binary tree= 2L
– Maximum number of nodes at level-2 in
a binary tree
= 22
=4
Thus, in a binary tree, maximum number
of nodes that can be present at level-2 =
4.
Binary Search Tree

– Binary Search Tree is a special kind of


binary tree in which nodes are arranged in
a specific order.
– In a binary search tree (BST), each node
contains-
• Only smaller values in its left sub tree
• Only larger values in its right sub tree
Number of Binary Search Trees-

Number of distinct binary search trees possible with 3


distinct keys
= 2×3C3 / 3+1
= 6C3 / 4
=5

If three distinct keys are A, B and C, then 5 distinct binary


search trees are-
Binary Search Tree Construction-
– Construct a Binary Search Tree (BST) for the following sequence of
numbers-
50, 70, 60, 20, 90, 10, 40, 100

– When elements are given in a sequence,


• Always consider the first element as the root node.
• Consider the given elements and insert them in the BST one by one.

– The binary search tree will be constructed as explained below-


Insert 60-
Insert 50- Insert 70-
•As 60 > 50, so insert 60 to the right of 50.
•As 70 > 50, so insert 70 to the right
•As 60 < 70, so insert 60 to the left of 70.
of 50.
Insert 20-
Insert 90-
•As 20 < 50, so insert 20 to the left of 50.
•As 90 > 50, so insert 90 to the right of 50.
•As 90 > 70, so insert 90 to the right of 70.
Insert 10-

•As 10 < 50, so insert 10 to the left of 50. Insert 40-


•As 10 < 20, so insert 10 to the left of 20.
•As 40 < 50, so insert 40 to the left of 50.
•As 40 > 20, so insert 40 to the right of 20.
Insert 100-

•As 100 > 50, so insert 100 to the right of 50.


•As 100 > 70, so insert 100 to the right of 70.
•As 100 > 90, so insert 100 to the right of 90.
BST Traversal- Consider the following binary search tree-

• A binary search tree is traversed in


exactly the same way a binary tree
is traversed.
• In other words, BST traversal is
same as binary tree traversal.
Preorder Traversal-

100 , 20 , 10 , 30 , 200 , 150 , 300

Inorder Traversal-

10 , 20 , 30 , 100 , 150 , 200 , 300

Postorder Traversal-

10 , 30 , 20 , 150 , 300 , 200 , 100


– Inorder traversal of a binary search tree always yields all
the nodes in increasing order.
• A binary search tree can be constructed using only preorder
or only postorder traversal result.
• This is because inorder traversal can be obtained by sorting
the given result in increasing order.
– The preorder traversal sequence of a binary search tree is-
– 30 , 20 , 10 , 15 , 25 , 23 , 39 , 35 , 42
– What one of the following is the postorder traversal sequence of
the same tree?
1.10 , 20 , 15 , 23 , 25 , 35 , 42 , 39 , 30
2.15 , 10 , 25 , 23 , 20 , 42 , 35 , 39 , 30
3.15 , 20 , 10 , 23 , 25 , 42 , 35 , 39 , 30
4.15 , 10 , 23 , 25 , 20 , 35 , 42 , 39 , 30
Solution-

In this question,
We are provided with the preorder traversal sequence.
We write the inorder traversal sequence by arranging all the numbers in
ascending order.

Then-
Preorder Traversal : 30 , 20 , 10 , 15 , 25 , 23 , 39 , 35 , 42
Inorder Traversal : 10 , 15 , 20 , 23 , 25 , 30 , 35 , 39 , 42

Now,
We draw a binary search tree using these traversal results.
Binary Search Tree Operations-

– Commonly performed operations on binary search tree are-


1.Search Operation
2.Insertion Operation
3.Deletion Operation
Search Operation-
– Search Operation is performed to
search a particular element in the
Binary Search Tree.
Rules-

For searching a given key in the BST,


•Compare the key with the value of root node.
•If the key is present at the root node, then return the root node.
•If the key is greater than the root node value, then recur for the
root node’s right subtree.
•If the key is smaller than the root node value, then recur for the
root node’s left subtree.
– Consider key = 45 has to be searched in the given BST.
• We start our search from the root node 25.
• As 45 > 25, so we search in 25’s right subtree.
• As 45 < 50, so we search in 50’s left subtree.
• As 45 > 35, so we search in 35’s right subtree.
• As 45 > 44, so we search in 44’s right subtree but 44 has no
subtrees.
• So, we conclude that 45 is not present in the above BST.
Insertion Operation-
– Insertion Operation is performed to insert an element in the Binary
Search Tree.
– Rules-
– The insertion of a new key always takes place as the child of some leaf
node.
– For finding out the suitable leaf node,
• Search the key to be inserted from the root node till some leaf node is
reached.
• Once a leaf node is reached, insert the key as child of that leaf node.
– Consider the following example where key = 40 is inserted
in the given BST-
• We start searching for value 40 from the root node 100.
• As 40 < 100, so we search in 100’s left subtree.
• As 40 > 20, so we search in 20’s right subtree.
• As 40 > 30, so we add 40 to 30’s right subtree.
Deletion Operation-
– Deletion Operation is performed to delete a particular
element from the Binary Search Tree.
– When it comes to deleting a node from the binary search
tree, following three cases are possible-
– Case-01: Deletion Of A Node Having No Child (Leaf Node)-
– Just remove / disconnect the leaf node that is to deleted
from the tree.
– Example-
– Consider the following example where node with value = 20
is deleted from the BST-
Case-02: Deletion Of A Node Having Only One Child-
– Just make the child of the deleting node, the child of its
grandparent.
Example-

Consider the following example where node with value = 30


is deleted from the BST-
Case-02: Deletion Of A Node Having Two Children-
A node with two children may be deleted from the BST in the
following two ways-
Method-01:
Visit to the right subtree of the deleting node.
Pluck the least value element called as inorder successor.
Replace the deleting element with its inorder successor.
– Example-
– Consider the following example where node with value = 15
is deleted from the BST
– Method-02:
• Visit to the left subtree of the deleting node.
• Pluck the greatest value element called as inorder predecessor.
• Replace the deleting element with its inorder predecessor.
– Example-
– Consider the following example where node with value = 15 is
deleted from the BST-
AVL Trees

• AVL trees are special kind of binary


search trees.
• In AVL trees, height of left subtree and
right subtree of every node differs by at This tree is an AVL tree because-
most one. •It is a binary search tree.
•The difference between height of left
• AVL trees are also called as self- subtree and right subtree of every node is
balancing binary search trees. at most one.
– This tree is not an AVL tree because-
The difference between height of left subtree and right subtree
of root node = 4 – 2 = 2.
• This difference is greater than one.
Balance Factor-

– In AVL tree,
• Balance factor is defined for every node.
• Balance factor of a node = Height of its left subtree – Height of
its right subtree
• Balance factor of every node is either 0 or 1 or -1.
AVL Tree Operations-

– Like BST Operations, commonly performed operations on AVL


tree are-
1.Search Operation
2.Insertion Operation
3.Deletion Operation
– After performing any operation on AVL tree, the balance factor of each
node is checked.
– There are following two cases possible-

– Case-01:
• After the operation, the balance factor of each node is either 0 or 1 or -1.
• In this case, the AVL tree is considered to be balanced.
• The operation is concluded.
– Case-02:
• After the operation, the balance factor of at least one node is
not 0 or 1 or -1.
• In this case, the AVL tree is considered to be imbalanced.
• Rotations are then performed to balance the tree.
AVL Tree Rotations-

– Rotation is the process of moving the nodes


to make tree balanced.
– There are 4 kinds of rotations possible in AVL
Trees-
1.Left Rotation (LL Rotation)
2.Right Rotation (RR Rotation)
3.Left-Right Rotation (LR Rotation)
4.Right-Left Rotation (RL Rotation)
Cases Of Imbalance And Their
Balancing Using Rotation Operations-
AVL Tree Properties-

– Property-01:
Maximum possible number of nodes in AVL tree of height H = 2^(H+1) – 1
Property-02:
– Minimum number of nodes in AVL Tree of height H is given by a
recursive relation N(H) = N(H-1) + N(H-2) + 1
– Base conditions for this recursive relation are-
• N(0) = 1
• N(1) = 2
– Property-03:
– Minimum possible height of AVL Tree using N nodes = ⌊log2N⌋
– Minimum possible height of AVL Tree using 8 nodes
= ⌊log28⌋
= ⌊log223⌋
= ⌊3log22⌋
= ⌊3⌋
=3
– Property-04:
• Maximum height of AVL Tree using N nodes is calculated
using recursive relation- N(H) = N(H-1) + N(H-2) + 1
– Base conditions for this recursive relation are-
• N(0) = 1
• N(1) = 2
– NOTE-
• If there are n nodes in AVL Tree, its maximum height can
not exceed 1.44log2n.
• In other words, Worst case height of AVL Tree with n nodes
= 1.44log2n.
Insertion in AVL Tree-

– Insertion Operation is performed to insert an element in the


AVL Tree.
– To insert an element in the AVL tree, follow the following
steps-
• Insert the element in the AVL tree in the same way the
insertion is performed in BST.
• After insertion, check the balance factor of each node of
the resulting tree.
Now, following two cases are possible-
Case-01:
– After the insertion, the balance factor of each node is either 0 or 1 or -1.
– In this case, the tree is considered to be balanced.
– Conclude the operation.
– Insert the next element if any.

– Case-02:
• After the insertion, the balance factor of at least one node is not 0 or 1 or -1.
• In this case, the tree is considered to be imbalanced.
• Perform the suitable rotation to balance the tree.
• After the tree is balanced, insert the next element if any.
– Rules To Remember-
– Rule-01:
– After inserting an element in the existing AVL tree,
• Balance factor of only those nodes will be affected that lies
on the path from the newly inserted node to the root node.
– Rule-02:
– To check whether the AVL tree is still balanced or not after
the insertion,
• There is no need to check the balance factor of every node.
• Check the balance factor of only those nodes that lies on
the path from the newly inserted node to the root node.
– Rule-03:
– After inserting an element in the AVL tree,
• If tree becomes imbalanced, then there exists one particular node in the tree by
balancing which the entire tree becomes balanced automatically.
• To re balance the tree, balance that particular node.

– To find that particular node,


• Traverse the path from the newly inserted node to the root node.
• Check the balance factor of each node that is encountered while traversing the path.
• The first encountered imbalanced node will be the node that needs to be balanced.

– To balance that node,


• Count three nodes in the direction of leaf node.
• Then, use the concept of AVL tree rotations to re balance the tree.
– Problem-
– Construct AVL Tree for the following sequence of numbers-
– 50 , 20 , 60 , 10 , 8 , 15 , 32 , 46 , 11 , 48
To balance the tree,
•Find the first imbalanced node on the path from the newly
inserted node (node 8) to the root node.
•The first imbalanced node is node 20.
•Now, count three nodes from node 20 in the direction of
leaf node.
•Then, use AVL tree rotation to balance the tree.
To balance the tree,
•Find the first imbalanced node on the path from the newly
inserted node (node 15) to the root node.
•The first imbalanced node is node 50.
•Now, count three nodes from node 50 in the direction of
leaf node.
•Then, use AVL tree rotation to balance the tree.

You might also like