0% found this document useful (0 votes)
7 views

Tree

Uploaded by

Vivek Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Tree

Uploaded by

Vivek Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 32

Tree Data Structures

Tree data structures are versatile and powerful ways to


organize and manipulate hierarchical information. In this
presentation, we'll explore their many applications and learn
how to use them effectively.

Dr. Subhash Chandra Gupta


Assistant Professor
Definition and Characteristics of Trees

1 Node-Based Structure 🌳 2 Hierarchical Relationship

A tree is a collection of nodes connected Trees represent a natural hierarchical


by edges, with a single root node and no structure, making them ideal for
cycles or loops. organizing data that has parent-child
relationships.
3 Multiple Branches 🌱 4 Recursive Nature

A tree can have multiple branches, with The recursive structure of trees allows
each node having at most one parent for efficient algorithms with logarithmic
and zero or more children. time complexity.
Binary Tree
•A tree is a non-linear data structure. It is considered as a powerful and very flexible data structure that can be
used for a wide variety of applications.
•A Tree is said to be a Binary Tree if all of its nodes have at-most 2 children. That is, all of its node can have
either no child, 1 child, or 2 child nodes.
Root: Root is the first node of the hierarchical data structure. It is present at the 0 th
level and this node represents the base address of the tree. As node A is the root of the
tree.

Nodes: Each data item in the tree is called a node like a node in a graph. It specifies
the information about the data and the links to other items. A, B, C, D, E, and F are the
nodes of the tree.

Degree: The number of nodes connected to a particular node ‘A’ is called the degree of
that node ‘A’. The degree of the leaf node is always one. As deg(A)=2, deg(B)=
deg(C)= deg(D)=3, deg(E)= deg(H)=1,
The degree of the tree is the maximum value of the degree of any node in the
tree. As deg(tree) =3.

Level: The root node of the tree has level 0. The level of any other node is one more
than the level of its parent. As Level(A)=0, Level(B)=Level(C)=1 and so on.

Depth: The maximum level of any leaf is called the depth of the binary tree. As the
depth of the tree would be 3 here.
Height: Height of the tree is the total number of levels from the root
node to the terminal/leaf node. As Height of the tree would be 4 here.

Ancestor: A node “A” is said to be an ancestor of node “B” if A is


either the father of B or the father of some ancestor of B.
For example; A is an ancestor of B, E, etc.

Descendent: A node “B” is said to be a left descendant of node “A” if


B is either the left son of A or the descendant of the left son of A.
For example; G, F, D, B, E are the left descendent to node A.
A node “B” is said to be a right descendant of node “A” if B is
either the right son of A or the descendant of the right son of A.
For example; C, H, I are the right descendent of node A.

Climbing: Is the process of traversing the tree from the leaf node to the
root node, also known as Bottom-up traversal.

Descending: Is the process of traversing the tree from the root node to
the leaf node, also known as Top-down traversal.
Properties of a Binary Tree
The maximum number of nodes at level 'l' of a binary tree is (2l - 1). Level of root is 1. This can be proved by
induction. For root, l = 1, number of nodes = 21-1 = 1 Assume that the maximum number of nodes on level l is 2l-1. Since in
Binary tree every node has at most 2 children, next level would have twice nodes, i.e. 2 * 2 l-1.

Maximum number of nodes in a binary tree of height 'h' is (2h – 1). Here height of a tree is the maximum
number of nodes on the root to leaf path. The height of a tree with a single node is considered as 1. This result can be derived
from point 2 above. A tree has maximum nodes if all levels have maximum nodes. So maximum number of nodes in a binary
tree of height h is 1 + 2 + 4 + .. + 2h-1. This is a simple geometric series with h terms and sum of this series is 2h – 1. In some
books, the height of the root is considered as 0. In that convention, the above formula becomes 2 h+1 – 1.

In a Binary Tree with N nodes, the minimum possible height or the minimum number of levels is
Log2(N+1). This can be directly derived from point 2 above. If we consider the convention where the height of a leaf node is
considered 0, then above formula for minimum possible height becomes Log2(N+1) – 1.

A Binary Tree with L leaves has at least (Log2L + 1) levels. A Binary tree has maximum number of leaves (and
minimum number of levels) when all levels are fully filled. Let all leaves be at level l, then below is true for number of leaves L.
L <= 2l-1 [From Point 1] l = Log2L + 1 where l is the minimum number of levels.

In a Binary tree in which every node has 0 or 2 children, the number of leaf nodes is always one more
than the nodes with two children. L = T + 1 Where L = Number of leaf nodes T = Number of internal nodes with two
children
Type of a Binary Tree
Full Binary Tree: A Binary Tree is full if every node has either 0 or 2 children. The following are examples
of a full binary tree. We can also say that a full binary tree is a binary tree in which all nodes except leave
nodes have two children. In a Full Binary, the number of leaf nodes is number of internal nodes plus 1.

Complete Binary Tree: A Binary Tree is a complete Binary Tree if all levels are completely filled except
possibly the last level and the last level has all keys as left as possible Following are the examples of
Complete Binary Trees:

Perfect Binary Tree: A Binary tree is a Perfect Binary Tree when all internal nodes have two children and
all the leave nodes are at the same level. Following are the examples of Perfect Binary Trees: A Perfect
Binary Tree of height h (where height is the number of nodes on the path from the root to leaf) has 2h – 1
node.
TYPES OF BINARY TREES
REPRESENTATION OF BINARY TREE IN MEMORY
TRAVERSING BINARY TREE

Pre-order: N-L-R (node(root)-left-right)


In-order: L-N-R (left-node(root)-right)
Post-order: L-R-N (left-right-node(root))
Unlike linear data structures (Array, Linked List, Queues, Stacks, etc.), which have only one logical
way to traverse them, trees can be traversed in different ways. Following are the generally used
ways for traversing trees:

Inorder (Left, Root, Right) : 4 2 5 1 3


Preorder (Root, Left, Right) : 1 2 4 5 3.
Postorder (Left, Right, Root) : 4 5 2 3 1
Level Order Traversal of a Binary Tree

We have seen the three basic traversals(Preorder, postorder, and Inorder) of a Binary Tree. We can also
traverse a Binary Tree using the Level Order Traversal.

In the Level Order Traversal, the binary tree is traversed level-wise starting from the first to last level
sequentially.

Consider the below binary tree:


The Level Order Traversal of the above Binary Tree will be: 10 20 30 40 50 60 70 80.
Algorithm: The Level Order Traversal can be implemented efficiently using a Queue.

• Create an empty queue q.


• Push the root node of tree to q. That is, q.push(root).
• Loop while the queue is not empty:
• Pop the top node from queue and print the node.
• Enqueue node's children (first left then right children) to q
• Repeat the process until queue is not empty.
Height of Binary Tree
Given a binary tree, the task is to find the height of the tree. Height of the tree is the number of
edges in the tree from the root to the deepest node, Height of the empty tree is 0.

Recursively calculate height of left and right subtrees of a node and assign height to the node
as max of the heights of two children plus 1. See below pseudo code and program for details.

maxDepth(‘1’) = max(maxDepth(‘2’), maxDepth(‘3’)) + 1 = 2 + 1


because recursively
maxDepth(‘2’) = max (maxDepth(‘4’), maxDepth(‘5’)) + 1 = 1 + 1 and (as height of both ‘4’ and
‘5’ are 1)
maxDepth(‘3’) = 1

Follow the below steps to Implement the idea:


• Recursively do a Depth-first search.
• If the tree is empty then return -1
• Otherwise, do the following
• Get the max depth of the left subtree recursively i.e. call maxDepth( tree->left-subtree)
• Get the max depth of the right subtree recursively i.e. call maxDepth( tree->right-subtree)
• Get the max of max depths of left and right subtrees and add 1 to it for the current node.
• Return max_depth.
Output
Height of tree is 3
Time Complexity: O(N)
Auxiliary Space: O(N) due to
recursive stack.
Operations on Trees
1 Traversing and Searching 🔍

There are multiple ways to


traverse a tree, such as Inorder,
Insertion and Deletion ➕ ➖ 2 Preorder, Postorder and Level-
New nodes can be inserted into a Order. Searching can be done
tree in an ordered manner, while recursively or iteratively,
existing nodes can be deleted depending on the tree's structure.
using their position or value.
These actions are crucial for
sorting and manipulating
hierarchical data.
Insertion in a Binary Tree
Problem: Given a Binary Tree and a Key. The task is to insert the key into the binary tree at first position available in level order.

The idea is to do iterative level order traversal of the given tree using a queue. If we find a node whose left child is empty, we make new key
as the left child of the node. Else if we find a node whose right child is empty, we make new key as the right child of that node. We keep
traversing the tree until we find a node whose either left or right child is empty.
Deletion in a Binary Tree
Problem: Given a Binary Tree and a node to be deleted from this tree. The task is to delete the given node
from it.
Examples:
Delete 10 in below tree
Output :
Delete 20 in below tree
Output :
While performing the delete operation on binary trees, there arise a few cases:
• The node to be deleted is a leaf node. That is it does not have any children.
• The node to be deleted is a internal node. That is it have left or right child.
• The node to be deleted is the root node.

In the first case 1, since the node to be deleted is a leaf node, we can simply
delete the node without any overheads. But in the next 2 cases, we will have
to take care of the children of the node to be deleted.

In order to handle all of the cases, one way to delete a node is to:

• Starting at the root, find the deepest and rightmost node in binary tree and node which we want to delete.
• Replace the deepest rightmost node’s data with the node to be deleted.
• Then delete the deepest rightmost node.
Introduction to Binary Search Trees
Binary Search Tree is a node-based binary tree data structure which has the following properties:

• The left subtree of a node contains only nodes with keys lesser than or equal to the node's key.
• The right subtree of a node contains only nodes with keys greater than the node's key.
• The left and right subtree each must also be a binary search tree. There must be no duplicate nodes.

Sample Binary Search Tree:

The above properties of Binary Search Tree provide an ordering among keys so that the operations like search, minimum
and maximum can be done fast in comparison to normal Binary Trees. If there is no ordering, then we may have to
compare every key to search a given key.
Searching a Key
struct node* search(struct node* root, int key)
Using the property of Binary Search Tree, we can
{
search for an element in O(h) time complexity
// Base Cases: root is null or key is present at root
where h is the height of the given BST.
if (root == NULL || root->key == key)
return root;
To search a given key in Binary Search Tree,
• first compare it with root, if (root->key < key)
• if the key is present at root, return root. // Key is greater than root's key
• If the key is greater than the root's key, we recur for return search(root->right, key);
the right subtree of the root node.
• Otherwise, we recur for the left subtree. // Key is smaller than root's key
return search(root->left, key);
}
Deletion in a Binary Search Tree
That is, given a Binary Search Tree and a node to be deleted. The task is to search that node in the given BST and delete it from the BST if it is
present.

When we delete a node, three cases may arise:


• Node to be deleted is leaf: Simply remove from the tree.

• Node to be deleted has only one child: Copy the child to the node and delete the child.

• Node to be deleted has two children: Find inorder successor of the node. Copy contents of the inorder successor to the node and delete
the inorder successor. Note that inorder predecessor can also be used.

Note: The inorder successor can be obtained by finding the minimum value in the right child of the node.
Self Balancing BST
Self-Balancing Binary Search Trees are height-balanced binary search trees that automatically keeps height as small as possible when
insertion and deletion operations are performed on tree. The height is typically maintained in order of Log n so that all operations take O(Log
n) time on average.

Examples :
Red Black Tree

AVL Tree:
Applications of BST
Applications of Binary Search tree:
• BSTs are used for indexing.
• It is also used to implement various searching algorithms.
• IT can be used to implement various data structures.
Real-time Application of Binary Search tree:
• BSTs are used for indexing in databases.
• It is used to implement searching algorithms.
• BSTs are used to implement Huffman coding algorithm.
• It is also used to implement dictionaries.
Advantages of Binary Search Tree:
• BST is fast in insertion and deletion when balanced.
• BST is efficient.
• We can also do range queries – find keys between N and M (N <= M).
• BST code is simple as compared to other data structures.
Disadvantages of Binary Search Tree:
• The main disadvantage is that we should always implement a balanced binary search tree. Otherwise
the cost of operations may not be logarithmic and degenerate into a linear search on an array.
• Accessing the element in BST is slightly slower than array.
• A BST can be imbalanced or degenerated which can increase the complexity.
Applications of Tree Data Structures
File Systems Representing Sorting and
and Directory Hierarchical Searching
Structures 📁 Relationships A l g o r i t h m s 🕵 ️‍♂️
Trees are a natural way Popular sorting algorithms
to represent the Trees are used to such as Heap sort use trees
filesystem hierarchy represent the structure to move elements to their
and the folders inside it, of an organization, the final order, while searching
allowing fast searches, hierarchy of a family, or algorithms like Tries use
and efficient the relationships trees to efficiently store and
manipulation of files between entities in retrieve words or keys.
and directories. various domains.
Advantages and Disadvantages
of Tree Data Structures
Advantages 👍 Disadvantages 👎
• Efficient and Fast • Memory Consumption
• Scalable and Adaptable • Complexity and Maintenance
• Flexible and Easy to Implement • Tree Imbalance and Degeneracy
Efficiency and Complexity Analysis: BST
Average Time Worst-Case Time Space Complexity
Complexity Complexity

Search O(log n) O(n) O(1)

Insert O(log n) O(n) O(n)

Delete O(log n) O(n) O(1)


Thank you!

You might also like