0% found this document useful (0 votes)
8 views22 pages

Unit III - Topic 3 - Binary Tree Adt

A Binary Tree is a data structure where each node has at most two children, represented by a root node with left and right pointers. Key operations include inserting, removing, searching, and traversing the tree using methods like pre-order, in-order, post-order, and level-order traversal. Various types of binary trees exist, including full, complete, perfect, and balanced trees, each with distinct properties and applications.

Uploaded by

ashwin88076
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
8 views22 pages

Unit III - Topic 3 - Binary Tree Adt

A Binary Tree is a data structure where each node has at most two children, represented by a root node with left and right pointers. Key operations include inserting, removing, searching, and traversing the tree using methods like pre-order, in-order, post-order, and level-order traversal. Various types of binary trees exist, including full, complete, perfect, and balanced trees, each with distinct properties and applications.

Uploaded by

ashwin88076
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 22

Unit III – Topic 3 - BINARY TREE ADT

BINARY TREE ADT

Binary Tree is defined as a tree data structure where each node has at most 2 children. Since each element in a binary tree can
have only 2 children, we typically name them the left and right child.

Binary Tree Representation


A Binary tree is represented by a pointer to the topmost node (commonly known as the “root”) of the tree, and the bottom-
most nodes are called leaves. A binary tree can be visualized as a hierarchical structure with the root at the top and the
leaves at the bottom. If the tree is empty, then the value of the root is NULL. Each node of a Binary Tree contains the
following parts:

1. Data
2. Pointer to left child
3. Pointer to right child

Basic Operation On Binary Tree:

 Inserting an element.

1
Unit III – Topic 3 - BINARY TREE ADT

 Removing an element.
 Searching for an element.
 Traversing the tree.

Auxiliary Operation On Binary Tree:

 Finding the height of the tree


 Find the level of a node of the tree
 Finding the size of the entire tree.

Binary Tree Traversals:


Tree Traversal algorithms can be classified broadly into two categories:
 Depth-First Search (DFS) Algorithms
 Breadth-First Search (BFS) Algorithms

Tree Traversal using Depth-First Search (DFS) algorithm can be further classified into three categories:

 Preorder Traversal (current-left-right): Visit the current node before visiting any nodes inside the left or right subtrees.
Here, the traversal is root – left child – right child. It means that the root node is traversed first then its left child and
finally the right child.
 Inorder Traversal (left-current-right): Visit the current node after visiting all nodes inside the left subtree but before
visiting any node within the right subtree. Here, the traversal is left child – root – right child. It means that the left
child is traversed first then its root node and finally the right child.
 Postorder Traversal (left-right-current): Visit the current node after visiting all the nodes of the left and right
subtrees. Here, the traversal is left child – right child – root. It means that the left child has traversed first then the
right child and finally its root node.
2
Unit III – Topic 3 - BINARY TREE ADT

Tree Traversal using Breadth-First Search (BFS) algorithm can be further classified into one category:

 Level Order Traversal: Visit nodes level-by-level and left-to-right fashion at the same level. Here, the traversal is
level-wise. It means that the most left child has traversed first and then the other children of the same level from left to
right have traversed.
Let us traverse the following tree with all four traversal methods:

Binary Tree

Pre-order Traversal of the above tree: 1-2-4-5-3-6-7


In-order Traversal of the above tree: 4-2-5-1-6-3-7
Post-order Traversal of the above tree: 4-5-2-6-7-3-1
Level-order Traversal of the above tree: 1-2-3-4-5-6-7

3
Unit III – Topic 3 - BINARY TREE ADT

Implementation of Binary Tree: (Exp.4.d)


Let us create a simple tree with 4 nodes. The created tree would be as follows.

#include <stdio.h>

#include <stdlib.h>

struct node

int data;

struct node* left;

4
Unit III – Topic 3 - BINARY TREE ADT

struct node* right;

};

// newNode() allocates a new node with the given data and NULL left and right pointers.

struct node* newNode(int data)

// Allocate memory for new node

struct node* node = (struct node*)malloc(sizeof(struct node));

// Assign data to this node

node->data = data;

// Initialize left and

// right children as NULL

node->left = NULL;

node->right = NULL;

return (node);

void display(struct node* root)

5
Unit III – Topic 3 - BINARY TREE ADT

{
if (root != NULL) {
display(root->left);
printf("%d ", root->data);
display(root->right);
}
}

int main()

// Create root

struct node* root = newNode(1);

/* following is the tree after above statement

/\

NULL NULL

*/

6
Unit III – Topic 3 - BINARY TREE ADT

root->left = newNode(2);

root->right = newNode(3);

/* 2 and 3 become left and right children of 1

/\

23

/\/\

NULL NULL NULL NULL

*/

root->left->left = newNode(4);

/* 4 becomes left child of 2

/\

23

/\/\

4 NULL NULL NULL

7
Unit III – Topic 3 - BINARY TREE ADT

/\

NULL NULL

*/

printf(“Binary Tree \n”);

display(root);

getchar();

return 0;

Output

Binary Tree

4213

Properties of Binary Tree


1. The maximum number of nodes at level ‘l’ of a binary tree is 2 l:
Note: Here level is the number of nodes on the path from the root to the node (including root and node). The level of the
root is 0
This can be proved by induction:

8
Unit III – Topic 3 - BINARY TREE ADT

For root, l = 0, number of nodes = 2 0 = 1


Assume that the maximum number of nodes on level ‘l’ is 2 l
Since in a Binary tree every node has at most 2 children, the next level would have twice nodes, i.e. 2 * 2 l

2. The Maximum number of nodes in a binary tree of height ‘h’ is 2 h – 1:


Note: Here the 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 the
maximum number of nodes in a binary tree of height h is 1 + 2 + 4 + .. + 2 h-1. This is a simple geometric series with h
terms and the sum of this series is 2 h– 1.
In some books, the height of the root is considered as 0. In this convention, the above formula becomes 2 h+1 – 1
3. In a Binary Tree with N nodes, the minimum possible height or the minimum number of levels is Log 2(N+1):
Each level should have at least one element, so the height cannot be more than N. A binary tree of height ‘h’ can have a
maximum of 2h – 1 nodes (previous property). So the number of nodes will be less than or equal to this maximum value

N <= 2h – 1
2h >= N+1
log2(2h) >= log2(N+1) (Taking log both sides)
hlog22 >= log2(N+1) (h is an integer)
h >= | log2(N+1) |
So the minimum height possible is | log 2(N+1) |
4. A Binary Tree with L leaves has at least | Log 2L |+ 1 levels:
A Binary tree has the maximum number of leaves (and a minimum number of levels) when all levels are fully filled. Let
all leaves be at level l, then below is valid for the number of leaves L
L <= 2l-1 [From Point 1] [Note: Here, consider level of root node as 1]
l = | Log2L | + 1
where l is the minimum number of levels
9
Unit III – Topic 3 - BINARY TREE ADT

5. In a Binary tree where every node has 0 or 2 children, the number of leaf nodes is always one more than nodes
with two children:
L=T+1
Where L = Number of leaf nodes
T = Number of internal nodes with two children
Proof:
No. of leaf nodes (L) i.e. total elements present at the bottom of tree = 2 h-1 (h is height of tree)
No. of internal nodes = {total no. of nodes} – {leaf nodes} = { 2 h – 1 } – {2h-1} = 2h-1 (2-1) – 1 = 2h-1 – 1
So , L = 2h-1
T = 2h-1 – 1
Therefore L = T + 1
Hence proved
6. In a non-empty binary tree, if n is the total number of nodes and e is the total number of edges, then e = n-1:
Every node in a binary tree has exactly one parent with the exception of the root node. So if n is the total number of nodes
then n-1 nodes have exactly one parent. There is only one edge between any child and its parent. So the total number of
edges is n-1.

Some extra properties of binary tree are:

 Each node in a binary tree can have at most two child nodes: In a binary tree, each node can have either zero, one, or
two child nodes. If a node has zero children, it is called a leaf node. If a node has one child, it is called a unary node. If
a node has two children, it is called a binary node.
 The node at the top of the tree is called the root node: The root node is the first node in a binary tree and all other
nodes are connected to it. All other nodes in the tree are either child nodes or descendant nodes of the root node.

10
Unit III – Topic 3 - BINARY TREE ADT

 Nodes that do not have any child nodes are called leaf nodes: Leaf nodes are the endpoints of the tree and have no
children. They represent the final result of the tree.
 The height of a binary tree is defined as the number of edges from the root node to the deepest leaf node: The height of
a binary tree is the length of the longest path from the root node to any of the leaf nodes. The height of a binary tree is
also known as its depth.
 In a full binary tree, every node except the leaves has exactly two children: In a full binary tree, all non-leaf nodes
have exactly two children. This means that there are no unary nodes in a full binary tree.
 In a complete binary tree, every level of the tree is completely filled except for the last level, which can be partially
filled: In a complete binary tree, all levels of the tree except the last level are completely filled. This means that there
are no gaps in the tree and all nodes are connected to their parent nodes.
 In a balanced binary tree, the height of the left and right subtrees of every node differ by at most 1: In a balanced
binary tree, the height of the left and right subtrees of every node is similar. This ensures that the tree is balanced and
that the height of the tree is minimized.
 The in-order, pre-order, and post-order traversal of a binary tree are three common ways to traverse the tree : In-order,
pre-order, and post-order are three different ways to traverse a binary tree. In-order traversal visits the left subtree, the
node itself, and then the right subtree. Pre-order traversal visits the node itself, the left subtree, and then the right
subtree. Post-order traversal visits the left subtree, the right subtree, and then the node itself.

Types of Binary Tree


Types of Binary Tree based on the number of children:
1. Full Binary Tree
2. Degenerate Binary Tree
3. Skewed Binary Trees

11
Unit III – Topic 3 - BINARY TREE ADT

1. Full Binary Tree


A Binary Tree is a full binary tree if every node has 0 or 2 children. The following are examples of a full binary tree. We
can also say a full binary tree is a binary tree in which all nodes except leaf nodes have two children.

A full Binary tree is a special type of binary tree in which every parent node/internal node has either two or no children. It
is also known as a proper binary tree.

2. Degenerate (or pathological) tree


A Tree where every internal node has one child. Such trees are performance-wise same as linked list. A degenerate or
pathological tree is a tree having a single child either left or right.

3. Skewed Binary Tree


A skewed binary tree is a pathological/degenerate tree in which the tree is either dominated by the left nodes or the right
nodes. Thus, there are two types of skewed binary tree: left-skewed binary tree and right-skewed binary tree.

12
Unit III – Topic 3 - BINARY TREE ADT

Types of Binary Tree On the basis of the completion of levels:


1. Complete Binary Tree
2. Perfect Binary Tree
3. Balanced Binary Tree

1. Complete Binary Tree


A Binary Tree is a Complete Binary Tree if all the levels are completely filled except possibly the last level and the last
level has all keys as left as possible.
A complete binary tree is just like a full binary tree, but with two major differences:
 Every level except the last level must be completely filled.
 All the leaf elements must lean towards the left.
 The last leaf element might not have a right sibling i.e. a complete binary tree doesn’t have to be a full binary tree.

13
Unit III – Topic 3 - BINARY TREE ADT

Complete Binary Tree

2. Perfect Binary Tree


A Binary tree is a Perfect Binary Tree in which all the internal nodes have two children and all leaf nodes are at the same
level.
A perfect binary tree is a type of binary tree in which every internal node has exactly two child nodes and all the leaf
nodes are at the same level.

14
Unit III – Topic 3 - BINARY TREE ADT

Perfect Binary Tree

In a Perfect Binary Tree, the number of leaf nodes is the number of internal nodes plus 1
L = I + 1 Where L = Number of leaf nodes, I = Number of internal nodes.
A Perfect Binary Tree of height h (where the height of the binary tree is the number of edges in the longest path from the
root node to any leaf node in the tree, height of root node is 0) has 2h+1 – 1 node.
An example of a Perfect binary tree is ancestors in the family. Keep a person at root, parents as children, parents of
parents as their children.
Refer to this article to read about more on Perfect Tree
3. Balanced Binary Tree
A binary tree is balanced if the height of the tree is O(Log n) where n is the number of nodes. For Example, the AVL tree
maintains O(Log n) height by making sure that the difference between the heights of the left and right subtrees is at most
1. Red-Black trees maintain O(Log n) height by making sure that the number of Black nodes on every root to leaf paths is

15
Unit III – Topic 3 - BINARY TREE ADT

the same and that there are no adjacent red nodes. Balanced Binary Search trees are performance-wise good as they
provide O(log n) time for search, insert and delete.

Example of Balanced and Unbalanced Binary Tree

It is a type of binary tree in which the difference between the height of the left and the right subtree for each node is either
0 or 1. In the figure above, the root node having a value 0 is unbalanced with a depth of 2 units.
Some Special Types of Trees:
On the basis of node values, the Binary Tree can be classified into the following special types:
1. Binary Search Tree
2. AVL Tree
3. Red Black Tree
4. B Tree
5. B+ Tree

16
Unit III – Topic 3 - BINARY TREE ADT

6. Segment Tree
Below Image Shows Important Special cases of binary Trees:

Binary Tree Special cases

1. Binary Search Tree


Binary Search Tree is a node-based binary tree data structure that has the following properties:
 The left subtree of a node contains only nodes with keys lesser than 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.

17
Unit III – Topic 3 - BINARY TREE ADT

2. AVL Tree
AVL tree is a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees
cannot be more than one for all nodes.

Example of AVL Tree shown below:


The below tree is AVL because the differences between the heights of left and right subtrees for every node are less than
or equal to 1

3. Red Black Tree


A red-black tree is a kind of self-balancing binary search tree where each node has an extra bit, and that bit is often
interpreted as the color (red or black). These colors are used to ensure that the tree remains balanced during insertions and
deletions. Although the balance of the tree is not perfect, it is good enough to reduce the searching time and maintain it
around O(log n) time, where n is the total number of elements in the tree. This tree was invented in 1972 by Rudolf
Bayer.

Red Black Tree


18
Unit III – Topic 3 - BINARY TREE ADT

4. B – Tree
A B-tree is a type of self-balancing tree data structure that allows efficient access, insertion, and deletion of data items. B-
trees are commonly used in databases and file systems, where they can efficiently store and retrieve large amounts of
data. A B-tree is characterized by a fixed maximum degree (or order), which determines the maximum number of child
nodes that a parent node can have. Each node in a B-tree can have multiple child nodes and multiple keys, and the keys
are used to index and locate data items.
5. B+ Tree
A B+ tree is a variation of the B-tree that is optimized for use in file systems and databases. Like a B-tree, a B+ tree also
has a fixed maximum degree and allows efficient access, insertion, and deletion of data items. However, in a B+ tree, all
data items are stored in the leaf nodes, while the internal nodes only contain keys for indexing and locating the data items.
This design allows for faster searches and sequential access of the data items, as all the leaf nodes are linked together in a
linked list.
6. Segment Tree
In computer science, a Segment Tree, also known as a statistic tree, is a tree data structure used for storing information
about intervals, or segments. It allows querying which of the stored segments contain a given point. It is, in principle, a
static structure; that is, it’s a structure that cannot be modified once it’s built. A similar data structure is the interval tree.
A segment tree for a set I of n intervals uses O(n log n) storage and can be built in O(n log n) time. Segment trees support
searching for all the intervals that contain a query point in time O(log n + k), k being the number of retrieved intervals or
segments.

Segment Tree
19
Unit III – Topic 3 - BINARY TREE ADT

Applications, Advantages and Disadvantages of Binary Tree


Application of Binary Trees:
 Search algorithms: Binary search algorithms use the structure of binary trees to efficiently search for a specific
element. The search can be performed in O(log n) time complexity, where n is the number of nodes in the tree.
 Sorting algorithms: Binary trees can be used to implement efficient sorting algorithms, such as binary search tree sort
and heap sort.
 Database systems: Binary trees can be used to store data in a database system, with each node representing a record.
This allows for efficient search operations and enables the database system to handle large amounts of data.
 File systems: Binary trees can be used to implement file systems, where each node represents a directory or file. This
allows for efficient navigation and searching of the file system.
 Compression algorithms: Binary trees can be used to implement Huffman coding, a compression algorithm that
assigns variable-length codes to characters based on their frequency of occurrence in the input data.
 Decision trees: Binary trees can be used to implement decision trees, a type of machine learning algorithm used for
classification and regression analysis.
 Game AI: Binary trees can be used to implement game AI, where each node represents a possible move in the game.
The AI algorithm can search the tree to find the best possible move.
Real-time applications of Binary Trees:
 DOM in HTML.
 File explorer.
 Used as the basic data structure in Microsoft Excel and spreadsheets.
 Editor tool: Microsoft Excel and spreadsheets.
 Evaluate an expression
 Routing Algorithms

20
Unit III – Topic 3 - BINARY TREE ADT

Advantages of Binary Tree:


 Efficient searching: Binary trees are particularly efficient when searching for a specific element, as each node has at
most two child nodes, allowing for binary search algorithms to be used. This means that search operations can be
performed in O(log n) time complexity.
 Ordered traversal: The structure of binary trees enables them to be traversed in a specific order, such as in-order, pre-
order, and post-order. This allows for operations to be performed on the nodes in a specific order, such as printing the
nodes in sorted order.
 Memory efficient: Compared to other tree structures, binary trees are relatively memory-efficient because they only
require two child pointers per node. This means that they can be used to store large amounts of data in memory while
still maintaining efficient search operations.
 Fast insertion and deletion: Binary trees can be used to perform insertions and deletions in O(log n) time complexity.
This makes them a good choice for applications that require dynamic data structures, such as database systems.
 Easy to implement: Binary trees are relatively easy to implement and understand, making them a popular choice for a
wide range of applications.
 Useful for sorting: Binary trees can be used to implement efficient sorting algorithms, such as heap sort and binary
search tree sort.
Disadvantages of Binary Tree:
 Limited structure: Binary trees are limited to two child nodes per node, which can limit their usefulness in certain
applications. For example, if a tree requires more than two child nodes per node, a different tree structure may be more
suitable.
 Unbalanced trees: Unbalanced binary trees, where one subtree is significantly larger than the other, can lead to
inefficient search operations. This can occur if the tree is not properly balanced or if data is inserted in a non-random
order.
 Space inefficiency: Binary trees can be space inefficient when compared to other data structures. This is because each
node requires two child pointers, which can be a significant amount of memory overhead for large trees.
 Slow performance in worst-case scenarios: In the worst-case scenario, a binary tree can become degenerate, meaning
that each node has only one child. In this case, search operations can degrade to O(n) time complexity, where n is the
number of nodes in the tree.
21
Unit III – Topic 3 - BINARY TREE ADT

 Complex balancing algorithms: To ensure that binary trees remain balanced, various balancing algorithms can be used,
such as AVL trees and red-black trees. These algorithms can be complex to implement and require additional
overhead, making them less suitable for some applications.

22

You might also like