0% found this document useful (0 votes)
16 views104 pages

Tree

Uploaded by

nahakrajesh3
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)
16 views104 pages

Tree

Uploaded by

nahakrajesh3
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/ 104

Trees - Introduction

• A tree is a nonlinear hierarchical data


structure that consists of nodes connected by
edges.
• Different tree data structures allow quicker
and easier access to the data as it is a non-
linear data structure.
• class TreeNode {

• int data;

• TreeNode left, right;


• TreeNode(int value) {

• data = value;

• left = right = null;

• }

• }


Properties of Trees
• There is one and only one path between every
pair of vertices in a tree.
• A tree with n vertices has n-1 edges.
• A graph is a tree if and if only if it is minimally
connected.
• Any connected graph with n vertices and n-1
edges is a tree.
Tree Applications
• Binary Search Trees(BSTs) are used to quickly
check whether an element is present in a set
or not.
• Heap is a kind of tree that is used for heap
sort.
• A modified version of a tree called Tries is
used in modern routers to store routing
information.
• Most popular databases use B-Trees and T-
Trees, which are variants of the tree structure
we learned above to store their data
• Compilers use a syntax tree to validate the
syntax of every program you write.
Tree terminologies
• Node - A node is an entity that contains a key
or value and pointers to its child nodes.
– The last nodes of each path are called leaf

nodes or external nodes that do not


contain a link/pointer to child nodes.
– The node having at least a child node is

called an internal node.


• Edge -It is the link between any two nodes.
• Root - It is the topmost node of a tree.
Tree terminologies
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.
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.
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.
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.
Siblings
• Nodes which belong to the same parent are
called as siblings.
• In other words, nodes with the same parent
are sibling nodes.
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.
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.
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.
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.
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
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.
• Depth of the root node = 0
• The terms “level” and “depth” are used
interchangeably.
Subtree
• In a tree, each child from a node forms a
subtree recursively.
• Every child node forms a subtree on its parent
node.
Forest

• A forest is a set of disjoint trees.

Types of Tree
• General Tree
• Binary Tree
• Binary Search Tree
• AVL Tree
• Red-Black Tree
• N-ary Tree
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.
Example
• Consider we want to draw all the binary trees
possible
• Number of binary trees possible with 3
unlabeled nodes
• = 2 x 3C3 / (3 + 1)
• = 6C3 / 4
• =5
Labeled Binary Tree

• A binary tree is labelled if all its nodes are


assigned a label.
Example
• Consider we want to draw all the binary
trees possible with 3 labeled nodes.
• 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
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.
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.
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.
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

• In order to perform any operation on a tree,


you need to reach to the specific node. The
tree traversal algorithm helps in visiting a
required node in the tree.
• Tree Traversal refers to the process of visiting
each node in a tree data structure exactly
once.
Tree traversal techniques
Tree Traversal

Depth First Traversal Breadth First Traversal

Preorder Traversal

Inorder Traversal

Postorder Traversal
Depth First Traversal

• Following three traversal techniques fall under


Depth First Traversal-
1. Preorder Traversal
2. Inorder Traversal
3. Postorder Traversal
Preorder Traversal

• Algorithm-
– Visit the root
– Traverse the left sub tree i.e. call Preorder
(left sub tree)
– Traverse the right sub tree i.e. call Preorder
(right sub tree)
Inorder Traversal
• Algorithm-
– Traverse the left sub tree i.e. call Inorder
(left sub tree)
– Visit the root
– Traverse the right sub tree i.e. call Inorder
(right sub tree)
Postorder Traversal
• Algorithm-
– Traverse the left sub tree i.e. call Postorder
(left sub tree)
– Traverse the right sub tree i.e. call
Postorder (right sub tree)
– Visit the root
Breadth First Search

• 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.
• void levelOrder(TreeNode root) {

• Queue<TreeNode> queue = new LinkedList<>();

• queue.add(root);

• while (!queue.isEmpty()) {

• TreeNode temp = queue.poll();

• System.out.print(temp.data + " ");

• if (temp.left != null) queue.add(temp.left);

• if (temp.right != null) queue.add(temp.right);

• }

• }
Binary Search Tree construction
• 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
BST construction
• Number of distinct binary search trees
possible with 3 distinct Nodes
= 2×3C3 / 3+1
= 6C3 / 4
=5
• If three distinct Nodes are A, B and C, then 5
distinct binary search trees are:
Example
• 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.
Practice problem
• Problem-01:
• A binary search tree is generated by inserting
in order of the following integers-
50, 15, 62, 5, 20, 58, 91, 3, 8, 37, 60, 24
• The number of nodes in the left subtree and
right subtree of the root respectively is _____.
– (4, 7)

– (7, 4)
– (8, 3)
– (3, 8)
Practice problem
• Problem-02:
• How many distinct binary search trees can be
constructed out of 4 distinct keys?
– 5

– 14

– 24
– 35
C code – BST construction
BST Traversal
•Inorder traversal of a binary search tree always
yields all the nodes in increasing order.
C Code – BST Traversal
Void inorder(node *root)
{
if(root!=NULL)
{ inorder(root->left);
printf("%d ",root-
>data);

}
C Code – BST Traversal
inorder(root->right);
}
void postorder(node *root)
{
if(root!=NULL)
{

}
C Code – BST Traversal
postorder(root->left);
postorder(root->right);
printf("%d ",root->data);
}
void preorder(node *root)
{

}
C Code – BST Traversal
if(root!=NULL)
{
printf("%d ",root-
>data); preorder(root-
>left);
preorder(root->right);

}
C Code – BST Traversal
}

}
Practice
• Suppose the numbers 7 , 5 , 1 , 8 , 3 , 6 , 0 , 9 ,
4 , 2 are inserted in that order into an initially
empty binary search tree. The binary search
tree uses the usual ordering on natural
numbers.
• What is the inorder traversal sequence of the
resultant tree?
A. 7 , 5 , 1 , 0 , 3 , 2 , 4 , 6 ,
8 , 9 B. 0 , 2 , 4 , 3 , 1 , 6 , 5
, 9 , 8 , 7 C. 0 , 1 , 2 , 3 , 4 , 5
,6,7,8,9
D.9 , 8 , 6 , 4 , 2 , 3 , 0 , 1 , 5 , 7
Problem-2
• The preorder traversal sequence of a binary
search tree is-
– 30 , 20 , 10 , 15 , 25 , 23 , 39 , 35 , 42
• Which one of the following is the postorder
traversal sequence of the same tree?
A. 10 , 20 , 15 , 23 , 25 , 35 , 42 , 39 ,
30 B. 15 , 10 , 25 , 23 , 20 , 42 , 35 ,
39 , 30
C. 15 , 20 , 10 , 23 , 25 , 42 , 35 , 39 ,
30 D. 15 , 10 , 23 , 25 , 20 , 35 , 42 ,
39 , 30
BST Operations

• Commonly performed binary search tree


operations are:
BST Operations

Search Operation Insertion Operation Deletion Operation

Search Operation
• Search Operation is performed to search a
particular element in the Binary Search Tree.
• 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.
C Code – BST Search Operation
struct node *search(struct node *node, int key)
{
// Return NULL if the tree is empty if
(node == NULL) return NULL; if (node-
>key == key) return node->data; if
(key < node->key)
search(node->left, key);
else
search(node->right, key);
}
Insertion operation

• 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.
C Code – Insertion Operation
// Create a
node struct
node
*newNode(int
item) {
struct node *temp = (struct
node *)malloc(sizeof(struct
node)); temp->key = item;
Case-
temp->left =
temp->right =
NULL; return
temp;
}
// Insert a node
struct node
*insert(struct node
*node, int key) { //
Return a new node
if the tree is empty
if (node == NULL)
return
newNode(key);
// Traverse to the
right place and insert
the node if (key <
node->key)
Case-
node->left = insert(node->left,
key);
else
node->right = insert(node-
>right, key);
return node;
}
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, 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.
Case-
02: Deletion Of A Node Having Only
One Child
• Consider the following example where node
with value = 30 is deleted from the BST.
Case-
03: Deletion Of A Node Having Two
Children
• Consider the following example where node
with value = 15 is deleted from the BST
• Method-1:
– 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.
• Method-2:
– Visit to the left subtree of the deleting
node.
Case-
– Pluck the greatest value element called as
inorder successor.
– Replace the deleting element with its
inorder successor.
C code – BST deletion
//Function to find minimum in a tree.
Node* FindMin(Node* root )
{
while(root->left != NULL) root = root ->left;
return root;
}

// Function to search a delete a value from tree.


struct Node* Delete(struct Node *root, int data) {
if(root == NULL) return root;
else if(data < root->data) root ->left = Delete(root ->left,data);
else if (data > root->data) root->right = Delete(root->right,data);
else {
// Case 1: No child
if(root->left == NULL && root ->right == NULL) {
free(root);
root = NULL;
}
//Case 2: One child
else if(root->left == NULL) {
struct Node *temp = root;
root = root->right;
free(temp);
}
else if(root->right == NULL) {
struct Node *temp = root;
root = root->left;
free(temp);
}
// case 3: 2 children
else {
struct Node *temp = FindMin(root->right);
root->data = temp->data;
root->right = Delete(root->right,temp ->data);
}
}
return root;
}

You might also like