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

Algorithm CH - 6 Tree

Uploaded by

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

Algorithm CH - 6 Tree

Uploaded by

tamirat birhanu
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 43

CHAPTER 6

TREE STRUCTURE

1
Point should be addressed
• Binary Tree and Binary Search Trees
• Basic Tree Operations
• Traversing in a Binary tree
• General Trees and Their Implementations

2
• Introduction
 A tree is a set of nodes and edges that connect pairs of
nodes.
 Tree can be defined as a collection of entities(nodes) linked
together to simulate a hierarchy.
 A tree is a non-linear data structure. It means you cannot
access an element of a tree in a straightforward manner.
 It is an abstract model of a hierarchical structure.
 Rooted tree has the following structure:
• One node distinguished as root.
• Every node C except the root is connected from exactly other node
P. P is C's parent, and C is one of P's children.
• There is a unique path from the root to each node.
• The number of edges in a path is the length of the path.

3
Tree Terminologies
 Consider the following tree.
A

B E F G

C D H I J

K L M

• Root: a node without a parent.  A


• Internal node: a node with at least one child. A, B, F, I, J
• External (leaf) node: a node without a child. C, D, E, H, K, L, M,
G
• Ancestors of a node: parent, grandparent, grand-grandparent, etc
of a node. Ancestors of K A, F, I
4
• Ancestors: any predecessor node on the path from root to the path
• Descendants of a node: children, grandchildren, grand-grandchildren etc of
a node.
• Descendant: any successor node on the path from that node to the leaf node
Descendants of F H, I, J, K, L, M

• Siblings: children of one parent. example C and D are sibling


• Depth of a node: number of ancestors or length of the path from the root to
the node.
Depth of H  2
• Height of a tree: depth of the deepest node.  3
• Subtree: a tree consisting of a node and its descendants.
• Path: A sequence of consecutive edges from source node to destination node

5
• Binary tree: a tree in which each node has at
most two children called left child and right
child.  

   

     

   

• Full binary tree: a binary tree where each node


has either 0 or 2 children.

   

    6
• Balanced binary tree: a binary tree where each node
except the leaf nodes has left and right children and all
the leaves are at the same level.
 

   

       

• Complete binary tree: a binary tree in which the


length from the root to any leaf node is either h or h-1
where h is the height of the tree. The deepest level
should also be filled from left to right.
 

   

      7
• Binary search tree (ordered binary tree): a binary tree
that may be empty, but if it is not empty it satisfies the
following.
• Every node has a key and no two elements have the same key.
• The keys in the right subtree are larger than the keys in the root.
• The keys in the left subtree are smaller than the keys in the root.
• The left and the right sub trees are also binary search trees.

10

6 15

4 8 14 18

7 12
16 19

11 13 8
• See the root, all the left descendants of the root are less than
the root value and all right descendant has a value greater
than the root.

Unordered Tree
• In a binary tree, when nodes are not in a particular order it is
called a unordered tree.

9
Operations on Binary Search Tree
• The following operations can be
implemented efficiently using a binary
search tree.
• Insert a key value
• Determine whether a key value is in the tree
• Remove a key value from the tree
• Print all of the key values in sorted order

10
Data Structure of a Binary Tree
Syntax
struct DataModel
{
Declaration of data fields
DataModel * Left, *Right;
};
DataModel *RootDataModelPtr=NULL;
Examples
Consider the following definition of binary search tree.
struct Node
{
int Num;
Node * Left, *Right;
};
Node *RootNodePtr=NULL; 11
Insertion
• When a node is inserted, the definition of binary
search tree should be preserved.
• Suppose there is a binary search tree whose root
node is pointed by RootNodePtr and we want to
insert a node (that stores 17) pointed by InsNodePtr.
Case1:- There is no data in the tree (i.e. RootNodePtr is
NULL).
• The node pointed by InsNodePtr should be made the
root node.
InsNodePtr RootNodePtr RootNodePtr

     

17
17
12
Case 2: There is data
• Search the appropriate position.
• Insert the node in that position.
InsNodePtr RootNodePtr RootNodePtr
   
 

InsertBST(RootNodePtr, InsNodePtr) 
17
10   10

6 6
15 15

4 8 4 8 14
14 18 18

7 12 7 12
16 19 16 19

11 13 11 13 17

13
Insert Code
struct Node
{
int num;
Node *left;
Node *right;
};
Node *RootNodeptr=NULL;
Void insertBST()
{
Node *InsNodeptr= New Node;
cout<<“Enter the number”<<endl;
cin>>InsNodeptr->num;
InsNodeptr->left==NULL;
InsNodeptr->right==NULL;
If(RootNodeptr==NULL)
14
RootNodeptr=InsNodeptr;
else
{ If(Np->right==NULL)
Node *Np=RootNodeptr; { Np->right=InsNodeptr;
int inserted=0;
While(inserted==0) Insereted=1;
{ }
If(Np->num>InsNodeptr->num)
else
{
If(Np->left==NULL) { Np=Np->right;
{ Np->left=InsNodeptr; }
Inserted=1;
} }
else }
{ Np=Np->left;
}
}
}
else
{ 15
Traversing
Binary search tree can be traversed in three ways.
• Preorder traversal - traversing binary tree in the order of parent,
left and right or < root >< left ><right >...
• Inorder traversal - traversing binary tree in the order of left,
parent and right or <left>< root ><right >..
• Postorder traversal - traversing binary tree in the order of left,
right and parent(root) or <left><right><root>.
RootNodePtr
Example:  

10

15
6

4 8 14 18

7 12
16 19

11 13 17 16
• Preorder traversal-10, 6, 4, 8, 7, 15, 14, 12, 11, 13, 18, 16, 17,
19
• Inorder traversal- 4, 6, 7, 8, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19
==> Used to display nodes in ascending order.
• Postorder traversal- 4, 7, 8, 6, 11, 13, 12, 14, 17, 16, 19, 18, 15,
10
Application of binary tree traversal
- Store values on leaf nodes and operators on internal nodes
• Preorder traversal- used to generate mathematical expression in
prefix notation.
• Inorder traversal- used to generate mathematical expression in
infix notation.
• Postorder traversal- used to generate mathematical expression
in postfix notation.
17
Example:
+

Preorder traversal - + – A * B C + D / E F  Prefix notation



+ Inorder traversal - A – B * C + D + E / F  Infix notation
Postorder traversal- A B C * – D E F / + +  Postfix notation
 
A *
D
/

B
C E F

18
Preorder traversal
1. Process the value in the root (e.g. print the root value).
2. Traverse the left subtree with a preorder traversal.
3. Traverse the right subtree with a preorder traversal.
Inorder traversal :-
prints the node values in ascending order:
1. Traverse the left subtree with an inorder traversal.
2. Process the value in the root (e.g. print the root value).
3. Traverse the right subtree with an inorder traversal.
Postorder traversal
1. Traverse the left subtree with a postorder traversal.
2. Traverse the right subtree with a postorder traversal.
3. Process the value in the root (e.g. print the root value).
19
Implementation of the Preorder traversals
void Preorder (Node *RootNodePtr)
{
if(RootNodePtr != NULL) 
{
cout << RootNodePtr->Num << endl;
Preorder(RootNodePtr->Left);
Preorder(RootNodePtr->Right);
}
}
20
Implementation of the Inorder traversals
void Inorder (Node * RootNodePtr)
{
if(RootNodePtr != NULL)
{
Inorder(RootNodePtr->Left);
cout << RootNodePtr->Num << endl;
Inorder(RootNodePtr->Right);
}
}
21
Implementation of the Postorder traversals
void Postorder(Node *RootNodePtr)
{
if(RootNodePtr != NULL)
{
Postorder(RootNodePtr->Left);
Postorder(RootNodePtr->Right);
cout << RootNodePtr->Num << endl;
}
}
22
Searching a data in BST
To search a node (whose Num value is X) in a
binary search tree (whose root node is pointed by
RootNodePtr). One of the three traversal methods
can be used.

23
Implementation:
int SearchBST (Node *RootNodePtr, int X)
{
if(RootNodePtr == NULL)
return 0; // 0 means (false, not found).
else
if(RootNodePtr ->Num == X)
return 1; // 1 means (true, found).
else if(RootNodePtr ->Num > X)
return(SearchBST(RootNodePtr ->Left, X));
else
return(SearchBST(RootNodePtr ->Right, X));
} 24
Finding Minimum value in a Binary Search Tree
• We can get the minimum value from a Binary Search Tree, by locating the
left most node in the tree.
• Then after locating the left most node, we display the value of that node.

25
Implementation:
int findMin(Node *RootNodePtr)
{
if(RootNodePtr == NULL)
return -1;
else
if(RootNodePtr ->Left == NULL)
return RootNodePtr ->Num;
else
return findMin(RootNodePtr ->Left);
} 26
Finding Maximum value in a Binary Search Tree
• We can get the maximum value from a Binary Search Tree, by
locating the right most node in the tree.
• Then after locating the right most node, we display the value
of that node.

27
Implementation:
int findMax(Node *RootNodePtr)
{
if(RootNodePtr == NULL)
return -1;
else
if(RootNodePtr ->Right == NULL)
return RootNodePtr ->Num;
else
return findMax(RootNodePtr ->Right);
}
28
Deleting from a BST
• There are a number of cases we may encounter when
deleting a node in a binary search tree.
• Among these cases:
– Deleting a root node.
– Deleting a leaf node.
– Deleting a node having only left child.
– Deleting a node having only right child.
– Deleting a node having both left and right child nodes.
• To delete a node (whose Num value is N) from binary
search tree (whose root node is pointed by RootNodePtr),
four cases should be considered.
• When a node is deleted the definition of binary search tree
should be preserved. 29
Case 1:  Deleting a leaf node (a node having no child), e.g. 7

30
Case 2:  Deleting a node having only one child, e.g. 2
• Approach 1:     Deletion by merging one of the following
is done:
– If the deleted node is the left child of its parent and the deleted
node has only the left child, the left child of the deleted node is
made the left child of the parent of the deleted node.    
– If the deleted node is the left child of its parent and the deleted
node has only the right child, the right child of the deleted node
is made the left child of the parent of the deleted node.       
– If the deleted node is the right child of its parent and the node to
be deleted has only the left child, the left child of the deleted
node is made the right child of the parent of the deleted node.    
– If the deleted node is the right child of its parent and the deleted
node has only the right child, the right child of the deleted node
is made the right child of the parent of the deleted node. 
31
32
• Approach 2: Deletion by copying the following is done:
– Copy the node containing the largest element in the left (or the
smallest element in the right) to the node containing the
element to be deleted
– Delete the copied Node

33
Case 3:  Deleting a node having two children, e.g. 6
• Approach 1:    Deletion by merging one of the following is done
– If the deleted node is the left child of its parent, one of the following is
done
• The left child of the deleted node is made the left child of the parent of the deleted
node, and
• The right child of the deleted node is made the right child of the node containing
largest element in the left of the deleted node

34
OR
– The right child of the deleted node is made the left
child of the parent of the deleted node, and
– The left child of the deleted node is made the left
child of the node containing smallest element in the
right of the deleted node
• If the deleted node is the right child of its parent,
one of the following is done
– The left child of the deleted node is made the right
child of the parent of the deleted node, and
– The right child of the deleted node is made the right
child of the node containing largest element in the left
of the deleted node
35
• OR
•  
– The right child of the deleted node is made the right child of the
parent of the deleted node, and
– The left child of the deleted node is made the left child of the node
containing smallest element in the right of the deleted node 36
• Approach 2: Deletion by copying the following is done:
• Copy the node containing the largest element in the left
(or the smallest element in the right) to the node
containing the element to be deleted
• Delete the copied node
Case 4:  Deleting the root node, 10
• Approach 1: Deletion by merging one of the following is
done:
• If the tree has only one node the root node pointer is
made to point to nothing (NULL)
• If the root node has left child
– the root node pointer is made to point to the left child
– the right child of the root node is made the right child of the
node containing the largest element in the left of the root node
37
• If root node has right child
– the root node pointer is made to point to the right
child
– the left child of the root node is made the left child of
the node containing the smallest element in the right
of the root node
• Approach 2: Deletion by copying the following is
done:
• Copy the node containing the largest element in
the left (or the smallest element in the right) to
the node containing the element to be deleted
• Delete the copied node
38
• Example: Suppose we want to delete Node 6 from
the binary search tree shown below. (Node 6 has
both left and right child nodes).

39
Binary search tree after deleting Node 6.

40
Node * minValueNode(Node* node)
{
Node* current = node;/* loop down to find the leftmost leaf */
while (current->Left != NULL)
current = current->Left;
return current;
}
Node* deleteNode(Node *RootNodePtr, int data)
{
if(RootNodePtr== NULL)
return RootNodePtr;
else if(data < RootNodePtr->Num)
RootNodePtr->Left = deleteNode(RootNodePtr->Left,data); 41
else if (data > RootNodePtr->Num)
RootNodePtr->Right = deleteNode(RootNodePtr->Right,data);
else
{
if(RootNodePtr->Left == NULL && RootNodePtr->Right == NULL)
// No child
{
delete RootNodePtr;
RootNodePtr= NULL;
}
else if(RootNodePtr->Left == NULL) //has only one child
{
Node *temp = RootNodePtr;
RootNodePtr= RootNodePtr->Right;
delete temp;
} 42
else if(RootNodePtr->Right == NULL)
{
Node *temp = RootNodePtr;
RootNodePtr= RootNodePtr->Left;
delete temp;
}
else
{
Node *temp = minValueNode(RootNodePtr->Right);
RootNodePtr->Num = temp->Num;
RootNodePtr->Right = deleteNode(RootNodePtr->Right,temp->Num);
}
}
return RootNodePtr;
} 43

You might also like