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

ICS121 - Data Structures I - Binary Tree

This document provides information about binary trees and binary search trees. It defines binary trees and describes their properties, types, representations, traversals, and applications. It also defines binary search trees and provides algorithms for operations like insertion, deletion, and traversal. Key points covered include defining full, complete, balanced, and skewed binary trees. Traversals discussed are preorder, inorder, and postorder. Applications mentioned include implementing hierarchical structures, priority queues, and search trees.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

ICS121 - Data Structures I - Binary Tree

This document provides information about binary trees and binary search trees. It defines binary trees and describes their properties, types, representations, traversals, and applications. It also defines binary search trees and provides algorithms for operations like insertion, deletion, and traversal. Key points covered include defining full, complete, balanced, and skewed binary trees. Traversals discussed are preorder, inorder, and postorder. Applications mentioned include implementing hierarchical structures, priority queues, and search trees.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

ICS121 – Data Structures I

Module 2 – Binary Tree

Dr. E.Silambarasan
Assistant Professor
Department of Cyber Security
Indian Institute of Information technology, Kottayam
Binary Trees – Insertion and Deletion of nodes, Tree Traversals,
Polish Notations, Red Black Trees, B-Trees, Heaps, Priority Queues.
Optimal binary search tree, Application problems on Optimal binary
search Tree
Tree:
• A tree is a non-linear data structure in which data is organized in branches.
• The data elements in tree are arranged in a sorted order.
• It imposes a hierarchical structure on the data elements.
• A Tree is a collection of nodes.
• The collection can be empty also.
• There is a specially designated node called Root Node.
• The Remaining nodes are partitioned in sub-trees like T1, T2,…Tn.
• The tree will have unique path from root node to its children or leaf node.
• The tree does not have cycle.

• Construct tree:
• The root of the tree is the node 60 at the top.
• Node 29 and 44 are the successors of the node 60.
• The nodes 6, 4, 12 and 67 are the terminal nodes.

• Advantage: Provides quick search, insert, and delete operations


• Disadvantage: Complicated deletion algorithm
Applications:
• Implementing the hierarchical structures in computer systems like directory
and file system.
• Implementing the navigation structure of a website.
• Code generation like Huffman’s code.
• Decision making in gaming applications.
• Implementation of priority queues for priority-based OS scheduling functions
• Parsing of expressions and statements in programming language compilers
• For storing data keys for DBMS for indexing
• Spanning trees for routing decisions in computer and communications
networks
• Hash trees
• path-finding algorithm to implement in AI, robotics and video games
applications
Properties of the Tree:
• The root of each sub-tree is a child of a Root node and root R is the parent of each root of the
sub-tree.
• Every node except the root node has one parent node and all the parent nodes have at least
one child.
• The node which has no child called leaf node or terminal nodes.
• The nodes with the same parent are called siblings.
• The depth of a node n is the unique path from root node to the node n.
• The height of a node n is the unique path from the node n to the root node.
• The height of the tree must be equal to the depth of the tree. Therefore H(T)= D(T).
• All the leaves at height zero and the depth of the root is zero.
• If there is a direct path from n1 to n2 then n1 is an ancestor of n2 and n2 is descendant of n1.
• A tree should not have multiple paths from node n1 to node n2.
Binary Tree:
• A binary tree is either empty, or it consists of a node called the root together with two binary
trees called the left subtree and the right subtree of the root.

Types:
Full Binary Tree/ Proper Binary Tree:
• A full Binary tree is a special type of binary tree in which every parent node/internal node has
either two or no children.

Complete Binary Tree:


• Every level must be completely filled.
• All the leaf elements must lean towards the left.
• The last leaf element might not have a right sibling.

Almost complete Binary Tree:


• A binary tree is called almost complete binary tree if it satisfies the following two properties:
1. All the leaf nodes should be present either at level d or d-1.
2. Any non leaf none if it has right sub-tree then there should be left sub-tree also.
Strictly Binary Tree:
• If every non leaf node in a binary tree has non empty left sub-tree and right sub-tree.

Perfect Binary Tree:


• All the internal nodes have two children and all leaf nodes are at the same level.

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.

A 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 the tree having a single child either left or right.

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.
Conversion of Tree to Binary tree:
• The left child of a node n will remain the left child of a node n and the right sibling will
become the right child of a node n.

Construction of Binary Tree:


1. Start with the first value, become the root node.
2. The next value will be added at the last position of the tree.
3. Always first add the left child of the parent then the right child to the parent.

Diameter of the tree:


• The number of nodes on the longest path between two end nodes.

Binary Search Tree:


• Binary tree in which a left child node value is less than the Parent node
• The right child node value of a node must be greater than equal to the parent node.
Note:
• The maximum number of nodes at level ‘l’ of a binary tree is 2l.
• The Maximum number of nodes in a binary tree of height ‘h’ is 2h – 1.
• In a Binary Tree with N nodes, minimum possible height or the minimum number of levels is
Log2(N+1).
• A Binary Tree with L leaves has at least | Log2L |+ 1 levels.
• In Binary tree where every node has 0 or 2 children, the number of leaf nodes is always one
more than nodes with two children.
• 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
Binary Tree Representation: • Find height of the tree
• Array • Find number of nodes in the tree.
• Linked list • Find the level of the tree
Node:
struct node Applications:
{ • In compilers, Expression Trees are
int data; used.
struct node *left,*right; • Huffman coding trees are used in
} data compression algorithms.
Basic Operations: • Priority Queue is used for searching
maximum or minimum in O(logN)
• Insertion time complexity.
• Deletion
• Searching
• Traversal
Other operations:
struct BTnode* createNode(value) struct BTnode* insertRightNode(struct BTnode* rootNode, int
value)
{
{
struct BTnode* newNode = malloc(sizeof(struct BTnode));
rootNode->rightNode = createNode(value);
newNode->data = value;
return rootNode->rightNode;
newNode->leftNode = NULL;
}
newNode->rightNode = NULL;
return newNode;
} Steps to construct Binary Tree:
//Root node : level 0 node
struct BTnode* insertLeftNode(struct BTnode* rootNode, int struct BTnode* rootNode = createNode(7);
value) //Left node of root: level 1 node
{ insertLeftNode(rootNode, 4);
//Right node of root
rootNode->leftNode = createNode(value);
return rootNode->leftNode; insertRightNode(rootNode, 8);
}
//level 2 nodes
insertLeftNode(rootNode->leftNode, 1);
insertRightNode(rootNode->rightNode, 5);
insertLeftNode(rootNode->leftNode, 6);
insertRightNode(rootNode->rightNode, 3);
Tree Traversal:
• Tree traversal is to visit all the nodes exactly once.
• Tree traversal is possible only for Simple tree and all the Binary trees.
• Tree traversal does not require algorithm.
• The traverse will start from root not and covers all the nodes from left to right.
Binary Tree Traversal:
• There are three types of binary tree traversals:
1. Pre-Order Traversal Root-L-R
2. In-Order Traversal L-Root-R
3. Post-Order Traversal L-R-Root
Tree traversal Algorithm: }

inorder(struct BTnode* rootNode) {


if (rootNode != NULL) {
inorder(rootNode->leftNode);
Write rootNode->data; postorder(struct BTnode* rootNode) {
inorder(rootNode->rightNode); if (rootNode != NULL) {
} postorder(rootNode->leftNode);
} postorder(rootNode->rightNode);
write rootNode->data;
preorder(struct BTnode* rootNode) { }
if (rootNode != NULL) { }
Write rootNode->data;
preorder(rootNode->leftNode);
preorder(rootNode->rightNode);
}
Deletion operation:

deleteTree(struct BTnode*root){
if(root == NULL)
return;
/* Delete Left sub-tree */
deleteTree(root->left);

/* Delete right sub-tree */


deleteTree(root->right);

/* At last, delete root node */


write root->data;
free(root);
}
Binary Search Tree: BSTNode *newNode(int val)

struct BSTNode {

{ BSTNode *temp;

int data; temp->key = item;

BSTNode *left, *right; temp->left = NULL;

}; temp->right = NULL;
return temp;
}
Binary Search Tree: else if (key < prev->key)
Insertion Operation: {
insert(BSTNode* &root, int key) prev->left = toinsert;
{ }
BSTNode* toinsert = newNode(key); else
BSTNode* curr = root; {
BSTNode* prev = NULL; prev->right = toinsert;
while (curr != NULL) }
{ }
prev = curr;
if (key < curr->key)
curr = curr->left;
else
curr = curr->right;
}
if (prev == NULL)
{
prev = toinsert;
root = prev;
}
Binary Search Tree:
Search Operation:
SEARCH(x, root)
if(root != null)
if(root->data == x)
write “search element found”
else if(root->data > x)
return SEARCH(x, root->left)
else if(root->data < x)
return SEARCH(x, root->right)
else
write” Search element is not found”
Binary Search Tree:
Finding Maximum/Minimum element Operation:

BSTNode* getmin( BSTNode* root)


{
BSTNode* curr = root;
while (curr && curr->left)
{
curr = curr->left;
}
return curr;
}
BSTNode* getmax( BSTNode* root)
{
BSTNode* curr = root;
while (curr && curr->right)
{
curr = curr->right;
}
return curr;
}
Binary Search Tree:
Deletion Operation:
Binary Search Tree:
Deletion Operation:
struct BSTNode* deleteNode(Node* root, int val)
{
//deletion at left subtree
if (val < root->data)
root->left = deleteNode(root->left, val);

//deletion at right subtree


else if (val > root->data)
root->right = deleteNode(root->right, val);

//deletion at root
else if(root->data==val)
{
//no child
if(root->left == NULL && root->right == NULL)
{
free(root);
}
Binary Search Tree:
Deletion Operation:
//one child
else if (root->left == NULL)
{
BSTNode* temp = root;
root=root->right;
free(temp);
}
else if (root->right == NULL)
{
BSTNode* temp = root;
root=root->left;
free(temp)
}
Binary Search Tree:
Deletion Operation:
//two children
else
{
BSTNode* temp = getMin(root->right);
root->data=temp->data;
root->right=deleteNode(root->right,temp->data); //removing duplicate
}
}
return root;
}
Height Balanced Binary Search Tree or AVL Tree:
• Adelson, Velskei and Landis
• Balancing Factor : -1, 0, 1
• Formula for Balancing Factor = Left subtree height – right subtree height
• Skewed Binary Search Tree - Search Complexity is O(h) or O(n)
• For balanced BST - Search Complexity is O(log n)
• AVL Tree performs 4 kinds of rotation for balancing the BST
• Single rotation
• Left rotation
• Right rotation
• Double Rotation
• Left-Right rotation
• Right- Left rotation
AVL Rotations: Single Rotation

Left Rotation

Right Rotation
AVL Rotations: Double Rotation
Left-Right Rotation

Right –Left Rotation


Node representation:
struct AVLnode
{
int data;
struct AVLnode *left, *right;
Int height;
};
//Create New Node
struct AVLnode * createNode(int val)
{
AVLnode* node;//allocate memory
node->data = val;
node->left = NULL;
node->right = NULL;
node->height = 0; // new node is initially, added at leaf
return(node);
}
//Insert Node
AVLnode* insert(AVLnode* node, int val)
{
//Perform the normal BST insertion
if (node == NULL)
return(createNode(val));
if (val < node->data)
node->left = insert(node->left, val);

else if (val > root-> data)


node->right = insert(node->right, val);

else // Equal keys are not allowed in BST


write “data is exist”;
// Update height of this ancestor node
node->height = 1 + max(height(node->left),
height(node->right));
//Get the balance factor of this ancestor node to check whether this node
became unbalanced
int balance = getBalance(node);
//Finding Balancing Factor
getBalance(Node *N)
{
if (N == NULL)
return 0;
else
return height(N->left) - height(N->right);
}
//finding Height
height(Node *N)
{
if (N == NULL)
return 0;
return N->height;
}
//Left Rotation
AVLnode *leftRotate(Node *x)
{
AVLnode *y = x->right;
AVLnode *T2 = y->left;

// Perform rotation
y->left = x;
x->right = T2;

// Update heights
x->height = max(height(x->left), height(x->right)) + 1;
y->height = max(height(y->left), height(y->right)) + 1;

// Return new root


return y;
}
//Right Rotation
AVLnode *rightRotate(Node *y)
{
AVLnode *x = y->left;
AVLnode *T2 = x->right;

// Perform rotation
x->right = y;
y->left = T2;

// Update heights
y->height = max(height(y->left), height(y->right)) + 1;
x->height = max(height(x->left), height(x->right)) + 1;

// Return new root


return x;
}
// Right rotation
if (balance > 1 && val < node->left-> data)
return rightRotate(node);

// Left Rotation
if (balance < -1 && val > node->right->data)
return leftRotate(node);

// Left Right Rotation


if (balance > 1 && val > node->left->data)
{
node->left = leftRotate(node->left);
return rightRotate(node);
}
// Right Left Rotation
if (balance < -1 && val < node->right->data)
{
node->right = rightRotate(node->right);
return leftRotate(node);
}

/* return the (unchanged) node pointer */


return node;
}
Assignment 3: AVL Tree
1. 50, 20, 60, 10, 8, 15, 32, 46, 11, 48
2. 5, 3, 10, 2, 4,7, 11, 1, 6, 9, 12, 8
3. 25, 20, 36, 10,22,30,40,12,28, 38, 48
4. 33,9,53,8,21,61,11
5. 33,13,5,3,11,21,61,8,9
6. 35, 9, 57, 5,23, 42, 91,37, 47, 96,51
Red Black Tree:
A red-black tree is a Binary Search Tree which has the following red-black properties:
• The ROOT node must be colored BLACK.
• Every node is either red or black.
• Every leaf (NULL) is black.
• If a node is red, then both its children are black.
• Implies that on any path from the root to a leaf, red nodes must not be adjacent. However, any
number of black nodes may appear in a sequence.
• Every simple path from a node to a descendant leaf contains the same number of black nodes.
• Every new node must be inserted with RED color.

• Basic red-black tree with the sentinel nodes added. Implementations of the red-black tree algorithms
will usually include the sentinel nodes as a convenient means of flagging that you have reached a leaf
node.
Insertion:
1. Recolor
2. Rotation
3. Rotation followed by Recolor
Steps:
1. Check whether tree is Empty.
2. If tree is Empty then insert the newNode as Root node with color Black and exit
from the operation.
3. If tree is not Empty then insert the newNode as leaf node with color Red.
4. If the parent of newNode is Black then exit from the operation.
5. If the parent of newNode is Red then check the color of parent node's sibling of
newNode.
1. If it is colored Black or NULL then make suitable Rotation and Recolor it.
2. If it is colored Red then perform Recolor and also check if grand parent of newNode is not root
node then recolor it and recheck.
Example: 8, 18, 5, 15, 17, 25, 40, 80
10,18, 7, 15, 16, 30, 25, 40, 60, 2, 1, 70
21, 17, 80, 5, 20, 25,98,2, 40
21,11,35,51,60
Red Black Tree – Deletion: o Reapply cases.

• Perform BST deletion • Case 5: DB’s S is black, S’s child who is far from DB is
black but near child to DB is red.
• Case 1: If the node to be deleted is red, just delete it
o Swap the colour of DB’s S and S’s child who is near
• Case 2: If root is Double Black (DB), just remove DB. to DB
o Rotate S in opposite direction to DB
• Case 3: If DB’s Sibling(S) is black and both the children
are black o Apply case 6

o Remove DB • Case 6: DB’s S is black , far child is red


o Add black to its Parent (P) o Swap the colour of P and S
▪ If P is red then it becomes black o Rotate P in DB’s direction
▪ If P is black then it becomes DB o Remove DB
o Make S red o Change colour of red child to black
o If still DB exists, apply other cases.

• Case 4: If DB’s sibling is red

o Swap the colour of P and its S


o Rotate P in DB direction

You might also like