0% found this document useful (0 votes)
3 views29 pages

Tree

The document provides an extensive overview of tree data structures, including definitions of key terminology such as root, parent, child, leaf, edge, and various types of trees like binary and complete trees. It also covers binary search trees, their operations (insert, search, traverse), and deletion cases, along with algorithms for these operations. Additionally, it includes code implementations for tree operations in C programming.

Uploaded by

deogirimemo
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)
3 views29 pages

Tree

The document provides an extensive overview of tree data structures, including definitions of key terminology such as root, parent, child, leaf, edge, and various types of trees like binary and complete trees. It also covers binary search trees, their operations (insert, search, traverse), and deletion cases, along with algorithms for these operations. Additionally, it includes code implementations for tree operations in C programming.

Uploaded by

deogirimemo
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/ 29

Tree Terminology

A tree is a hierarchical data structure defined as a collection of nodes. Nodes


represent value and nodes are connected by edges. A tree has the following
properties:

1. The tree has one node called root. The tree originates from this, and
hence it does not have any parent.
2. Each node has one parent only but can have multiple children.
3. Each node is connected to its children via edge.
Terminology Description Example From Diagram

Root is a special node in a tree. The


Root entire tree originates from it. It does Node A
not have a parent.

Parent node is an immediate


Parent Node B is parent of D & E
predecessor of a node.

All immediate successors of a node


Child Node D & E are children of B
are its children.

Node which does not have any child H, I, J, F and G are leaf
Leaf
is called as leaf nodes

Edge is a connection between one


Line between A & B is
Edge node to another. It is a line between
edge
two nodes or a node and a leaf.

Nodes with the same parent are


Siblings D & E are siblings
called Siblings.

Path is a number of successive


Path / A – B – E – J is path
edges from source node to
Traversing from node A to E
destination node.

A, B, C, D & E can have


height. Height of A is no.
Height of a node represents the
Height of of edges between A and
number of edges on the longest path
Node H, as that is the longest
between that node and a leaf.
path, which is 3. Height
of C is 1

Level of a node represents the


generation of a node. If the root node
Levels of Level of H, I & J is 3.
is at level 0, then its next child node
node Level of D, E, F & G is 2
is at level 1, its grandchild is at level
2, and so on

Degree of Degree of a node represents the Degree of D is 2 and of E


Node number of children of a node. is 1

Descendants of a node represent Nodes D, H, I represent


Sub tree
subtree. one subtree.
 Main applications of trees include:
1. Manipulate hierarchical data.
2. Make information easy to search (see tree traversal).
3. Manipulate sorted lists of data.
4. As a workflow for compositing digital images for visual effects.
5. Router algorithms
6. Form of a multi-stage decision-making (see business chess).

 Types of Trees

Types of trees depend on the number of children a node has. There are two
major tree types:
 General Tree: A tree in which there is no restriction on the number of
children a node has, is called a General tree. Examples are Family tree,
Folder Structure.

 Binary Tree: In a Binary tree, every node can have at most 2 children, left
and right. In diagram below, B & D are left children and C, E & F are
right children.
 Full/ proper/ strict Binary tree

The full binary tree is also known as a strict binary tree. The tree can only
be considered as the full binary tree if each node must contain either 0 or 2
children. The full binary tree can also be defined as the tree in which each
node must contain 2 children except the leaf nodes.

 Complete Binary Tree

The complete binary tree is a tree in which all the nodes are completely filled
except the last level. In the last level, all the nodes must be as left as
possible. In a complete binary tree, the nodes should be added from the left.

Let's create a complete binary tree.


 Perfect Binary tree: It is a binary tree in which all interior nodes have
two children and all leaves have the same depth or same level.

 Degenerate / Skewed Binary Tree

The degenerate binary tree is a tree in which all the internal nodes have only
one children. It is also known as a ”„skewed tree “.

In Left-Skewed tree all the nodes have a left child only.


In Right Skewed tree all the nodes have a right child only.

LEFT SKEWED TREE RIGHT SKEWED TREE


 Binary Tree Representations
A binary tree data structure is represented using two methods. Those
methods are as follows...
1. Array Representation
2. Linked List Representation

1. Array Representation of Binary Tree


In array representation of a binary tree, we use one-dimensional array (1-D
Array) to represent a binary tree.
To represent tree using an array, the numbering of nodes starts from 0.

Consider the above example of a binary tree and it is represented as


follows...

2 3

4 6 7
5

8 9 13

Array Size = 2d = 24 =16

15 A B C D F G H I J K
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

 Index of left child of node i =2 X i


 Index of Right child of node i = 2 X i + 1
 Index of parent of node i = i / 2
2. Linked List Representation of Binary Tree
We use a double linked list to represent a binary tree. In a double
linked list, every node consists of three fields. First field for storing left child
address, second for storing actual data and third for storing right child
address.

C
B

G H
D F

K
I J
 Binary Search Tree Representation

Binary Search tree exhibits a special behavior. A node's left child must have
a value less than its parent's value and the node's right child must have a
value greater than its parent value and it is true for all nodes.

 Binary Search Tree Basic Operations

The basic operations that can be performed on a binary search tree data
structure, are the following −
 Insert − Inserts an element in a tree/create a tree.
 Search − Searches an element in a tree.
 Preorder Traversal − Traverses a tree in a pre-order manner.
 Inorder Traversal − Traverses a tree in an in-order manner.
 Postorder Traversal − Traverses a tree in a post-order manner.
 Deletion – Deletes elements from tree

 Insert Operation

This is a very straight forward operation. First, the root node is inserted, and
then the next value is compared with the root node. If the value is greater
than root, it is added to the right subtree, and if it is lesser than the root, it
is added to the left subtree.

Algorithm
IF ROOT==NULL THEN
ROOT=P;
ELSE
IF P->DATA < R->DATA && R->LEFT==NULL THEN
R->LEFT=P
PRINTF("%D INSERTED",P->DATA)
ELSE IF P->DATA < R->DATA && R->LEFT!=NULL THEN
INSERT(R->LEFT,P)
ELSE IF P->DATA >= R->DATA && R->RIGHT==NULL THEN
R->RIGHT=P
PRINTF("%D INSERTED",P->DATA)
ELSE IF P->DATA >= R->DATA && R->RIGHT!=NULL THEN
INSERT(R->RIGHT,P)
END IF
END IF
 Create the binary search tree using the following data elements.

43, 10, 79, 90, 12, 54, 11, 9, 50

1. Insert 43 into the tree as the root of the tree.


2. Read the next element, if it is lesser than the root node element, insert
it as the root of the left sub-tree.
3. Otherwise, insert it as the root of the right of the right sub-tree.

The process of creating BST by using the given elements, is shown in the
image below.
Example 1: Create Binary Search Tree from following Nodes

25 , 20 , 17 , 35, 22, 47, 34 , 19 , 27

25  root of tree

20

17

35

22

47

34

19

27

Example 2: 8,10,3,6,1,14,4,7,13
Example 3: 60, 41 , 74 ,65, 16, 53, 25 ,46 , 55 ,63 , 70, 64, 62, 42

 Search Operation

Whenever an element is to be searched, start searching from the root node,


then if the data is less than the key value, search for the element in the left
subtree. Otherwise, search for the element in the right subtree. Follow the
same algorithm for each node.
Algorithm

INT FLAG=0;
WHILE R!= NULL
IF R->DATA==KEY THEN
FLAG=1
BREAK
ELSE
IF KEY < R->DATA THEN
R=R->LEFT
ELSE
R=R->RIGHT
END IF
END IF
END WHILE
RETURN FLAG;
 Tree Traversal
Traversal is a process to visit all the nodes of a tree and may print their
values too. Because, all nodes are connected via edges (links) we always
start from the root (head) node. That is, we cannot randomly access a node
in a tree. There are three ways which we use to traverse a tree −

 In-order Traversal
 Pre-order Traversal
 Post-order Traversal

 In-order Traversal

In this traversal method, the left subtree is visited first, then the root and
later the right sub-tree. We should always remember that every node may
represent a subtree itself.
If a binary tree is traversed in-order, the output will produce sorted key
values in an ascending order.

We start from A, and following in-order traversal, we move to its left


subtree B. B is also traversed in-order. The process goes on until all the
nodes are visited. The output of inorder traversal of this tree will be −
D→B→E→A→F→C→G
 Algorithm
Until all nodes are traversed −
Step 1 − Recursively traverse left subtree.
Step 2 − Visit root node.
Step 3 − Recursively traverse right subtree.
 Pre-order Traversal

In this traversal method, the root


node is visited first, then the left
subtree and finally the right subtree.

We start from A, and following pre-order traversal, we first visit A itself and
then move to its left subtree B. B is also traversed pre-order. The process
goes on until all the nodes are visited. The output of pre-order traversal of
this tree will be −
A→B→D→E→C→F→G
 Algorithm
Until all nodes are traversed −
Step 1 − Visit root node.
Step 2 − Recursively traverse left subtree.
Step 3 − Recursively traverse right subtree.

 Post-order Traversal

In this traversal method, the root node is


visited last, hence the name. First we traverse
the left subtree, then the right subtree and
finally the root node.

We start from A, and following Post-order traversal, we first visit the left
subtree B. B is also traversed post-order. The process goes on until all the
nodes are visited. The output of post-order traversal of this tree will be −
D→E→B→F→G→C→A
 Algorithm
Until all nodes are traversed −
Step 1 − Recursively traverse left subtree.
Step 2 − Recursively traverse right subtree.
Step 3 − Visit root node.
 Delete Operations
 Case I
In the first case, the node to be deleted is the leaf node. In such a case,
simply delete the node from the tree.

 Case II
In the second case, the node to be deleted lies has a single child node. In
such a case follow the steps below:
1. Replace that node with its child node.
2. Remove the child node from its original position.
 Case III
In the third case, the node to be deleted has two children. In such a case
follow the steps below:
1. Get the inorder successor of that node.
2. Replace the node with the inorder successor.
3. Remove the inorder successor from its original position.
 SIMPLE IMPLEMENTATION OF BINARY TREE

/* Binary Tree*/
#include <stdio.h>
#include <conio.h>
#include<stdlib.h>

struct Tree
{
int data;
struct Tree* left;
struct Tree* right;
}*root;

/*Inserting a New Node in a tree*/


void Insert(struct Tree *r,struct Tree *p)
{
if(root==NULL)
root=p;
else
{
if(p->data < r->data && r->left==NULL)
{
r->left=p;
printf("%d Inserted",p->data);
}
else if(p->data < r->data && r->left!=NULL)
Insert(r->left,p);
else if (p->data >= r->data && r->right==NULL)
{
r->right=p;
printf("%d Inserted",p->data);
}
else if (p->data >= r->data && r->right!=NULL)
Insert(r->right,p);
}
}
/* Searching Node in a tree*/
int SearchTree(struct Tree *r,int key)
{
int flag=0;
while(r!=NULL)
{
if(r->data==key)
{
flag=1;
break;
}
else
{
if(key < r->data)
r=r->left;
else
r=r->right;
}
}
return flag;
}

/* Inorder traversal */
void InorderTraversal(struct Tree* r)
{
if(r != NULL)
{ //return;
InorderTraversal(r->left);
printf("%2d ->", r->data);
InorderTraversal(r->right);
}
}

/* Preorder traversal */
void PreorderTraversal(struct Tree* r)
{
if(r!=NULL)
{
printf("%2d ->", r->data);
PreorderTraversal(r->left);
PreorderTraversal(r->right);
}
}
/* Postorder traversal */
void PostorderTraversal(struct Tree* r)
{
if (r != NULL)
{
PostorderTraversal(r->left);
PostorderTraversal(r->right);
printf("%2d ->", r->data);
}
}

void main()
{
struct Tree *p;
int choice,n,key;
root=NULL;
do
{
clrscr();
printf(" Tree Operations \n");
printf("**************************\n");
printf(" 1.INSERT-TREE\n");
printf(" 2.PREORDER TRAVERSE\n");
printf(" 3.INORDER TRAVERSE\n");
printf(" 4.POSTORDER TRAVERSE\n");
printf(" 5.ALL TRAVERSAL\n");
printf(" 6.SEARCH KEY\n");
printf(" 7.EXIT\n");
printf("****************************\n");
printf("ENTER YOUR CHOICE : ");
scanf("%d",&choice);
switch(choice)
{
case 1: printf("Enter Data : ");
scanf("%d",&n);
p=(struct Tree*)malloc(sizeof(struct Tree));
p->data=n;
p->left=p->right=NULL;
Insert(root,p);
getch(); break;
case 2: if(root==NULL)
printf("Tree is Empty");
else
{
printf("\nPreorder :");
PreorderTraversal(root);
}
getch(); break;
case 3: if(root==NULL)
printf("Tree is Empty");
else
{
printf("\nInorder :");
InorderTraversal(root);
}
getch(); break;
case 4: if(root==NULL)
printf("Tree is Empty");
else
{
printf("\nPostorder :");
PostorderTraversal(root);
}
getch(); break;
case 5: printf("\nPreorder :");
PreorderTraversal(root);
printf("\nInorder :");
InorderTraversal(root);
printf("\nPostorder :");
PostorderTraversal(root);
getch();break;
case 6: printf("Enter key to search : ");
scanf("%d",&key);
if(root==NULL)
printf("Tree is Empty");
else
{
if(SearchTree(root,key))
printf("%d found",key);
else
printf("%d not found",key);
}
getch(); break;
case 7: break;
default:printf("Invalid Choice : ");
}
}while(choice!=7);
getch();
}
 Expression Tree
Expression Tree is used to represent expressions. The expression tree is a
binary tree in which each internal node corresponds to the operator and
each leaf node corresponds to the operand so for example expression tree
for 3 + ((5+9)*2) would be:

Example1 : 3+((5+9)*2)

Example2: a + (b * c) + d * (e + f)

Example 3: 2*3/(2-1)+5*(4-1)
 COMPLETE IMPLEMENTATION OF BINARY TREE
/* Binary Tree*/
#include <stdio.h>
#include <conio.h>
#include<stdlib.h>

struct Tree
{
int data;
struct Tree* left;
struct Tree* right;
}*root;

/* inserting node in binary tree */


void Insert(struct Tree *r,struct Tree *p)
{
if(root==NULL)
root=p;
else
{
if(p->data < r->data && r->left==NULL)
{
r->left=p;
printf("%d Inserted",p->data);
}
else if(p->data < r->data && r->left!=NULL)
Insert(r->left,p);
else if (p->data >= r->data && r->right==NULL)
{
r->right=p;
printf("%d Inserted",p->data);
}
else if (p->data >= r->data && r->right!=NULL)
Insert(r->right,p);
}
}
/* searchin node in binary tree */
int SearchTree(struct Tree *r,int key)
{
int flag=0;
while(r!=NULL)
{
if(r->data==key)
{
flag=1;
break;
}
else
{
if(key < r->data)
r=r->left;
else
r=r->right;
}
}
return flag;
}

/* Inorder traversal */
void InorderTraversal(struct Tree* r)
{
if(r != NULL)
{ //return;
InorderTraversal(r->left);
printf("%2d ->", r->data);
InorderTraversal(r->right);
}
}

/* Preorder traversal */
void PreorderTraversal(struct Tree* r)
{
if(r!=NULL)
{
printf("%2d ->", r->data);
PreorderTraversal(r->left);
PreorderTraversal(r->right);
}
}

/* Postorder traversal */
void PostorderTraversal(struct Tree* r)
{
if (r != NULL)
{
PostorderTraversal(r->left);
PostorderTraversal(r->right);
printf("%2d ->", r->data);
}
}

/* Counting nodes in binary tree */


static int count=0;
int CountNodes(struct Tree *r)
{
if(r != NULL)
{
CountNodes(r->left);
count++;
CountNodes(r->right);
}
return count;
}

/* Returns the count of leaf nodes in a binary tree */


int CountLeafNodes(struct Tree *r)
{
if(r == NULL) /* Empty(NULL) Tree */
return 0;

if(r->left == NULL && r->right == NULL) /* Check for leaf node */


return 1;

/* return the sum of leaf nodes in left and right sub-tree */


return CountLeafNodes(r->left) + CountLeafNodes(r->right);
}

/*find leftmost node */


int getRightMin(struct Tree *root)
{
struct Tree *temp = root;

//min value should be present in the left most node.


while(temp->left != NULL){ temp = temp->left;}

return temp->data;
}

/* Deleting node from tree */


struct Tree *DeleteNode(struct Tree *root, int val)
{
/*
* If the node becomes NULL, it will return NULL
* Two possible ways which can trigger this case
* 1. If we send the empty tree. i.e root == NULL
* 2. If the given node is not present in the tree.
*/
if(root == NULL)
return NULL;
/*
* If root->key < val. val must be present in the right subtree
* So, call the above remove function with root->right
*/
if(root->data < val)
root->right = DeleteNode(root->right,val);
/*
* if root->key > val. val must be present in the left subtree
* So, call the above function with root->left
*/
else if(root->data > val)
root->left = DeleteNode(root->left,val);
/*
* This part will be executed only if the root->key == val
* The actual removal starts from here
*/
else
{
/*
* Case 1: Leaf node. Both left and right reference is NULL
* replace the node with NULL by returning NULL to the calling
pointer.
* free the node
*/
if(root->left == NULL && root->right == NULL)
{
printf("%d deleted",root->data);
free(root);
return NULL;
}
/*
* Case 2: Node has right child.
* replace the root node with root->right and free the right node
*/
else if(root->left == NULL)
{
struct Tree *temp = root->right;
free(root);
return temp;
}
/*
* Case 3: Node has left child.
* replace the node with root->left and free the left node
*/
else if(root->right == NULL)
{
struct Tree *temp = root->left;
free(root);
return temp;
}
/*
* Case 4: Node has both left and right children.
* Find the min value in the right subtree
* replace node value with min.
* And again call the remove function to delete the node which has the
min value.
* Since we find the min value from the right subtree call the remove
function with root->right.
*/
else
{
int rightMin = getRightMin(root->right);
root->data = rightMin;
root->right = DeleteNode(root->right,rightMin);
}

}
//return the actual root's address
return root;
}

void main()
{
struct Tree *p;
int choice,n,key;
root=NULL;
do
{
clrscr();
printf(" Tree Operations \n");
printf("**************************\n");
printf(" 1.INSERT-TREE\n");
printf(" 2.PREORDER TRAVERSE\n");
printf(" 3.INORDER TRAVERSE\n");
printf(" 4.POSTORDER TRAVERSE\n");
printf(" 5.ALL TRAVERSAL\n");
printf(" 6.SEARCH KEY\n");
printf(" 7.DELETE NODE\n");
printf(" 8.COUNT NODES\n");
printf(" 9.COUNT LEAF NODES\n");
printf(" 10.EXIT\n");
printf("****************************\n");
printf("ENTER YOUR CHOICE : ");
scanf("%d",&choice);
switch(choice)
{
case 1: printf("Enter Data : ");
scanf("%d",&n);
p=(struct Tree*)malloc(sizeof(struct Tree));
p->data=n;
p->left=p->right=NULL;
Insert(root,p);
getch(); break;
case 2: if(root==NULL)
printf("Tree is Empty");
else
{
printf("\nPreorder :");
PreorderTraversal(root);
}
getch(); break;
case 3: if(root==NULL)
printf("Tree is Empty");
else
{
printf("\nInorder :");
InorderTraversal(root);
}
getch(); break;
case 4: if(root==NULL)
printf("Tree is Empty");
else
{
printf("\nPostorder :");
PostorderTraversal(root);
}
getch(); break;
case 5: if(root==NULL)
printf("Tree is Empty");
else
{
printf("\nPreorder :");
PreorderTraversal(root);
printf("\nInorder :");
InorderTraversal(root);
printf("\nPostorder :");
PostorderTraversal(root);
}
getch();break;
case 6: if(root==NULL)
printf("Tree is Empty");
else
{
printf("Enter key to search : ");
scanf("%d",&key);

if (SearchTree(root,key))
printf("%d found",key);
else
printf("%d not found",key);
}
getch(); break;
case 7:if(root==NULL)
printf("Tree is Empty");
else
{
printf("Enter Node to Delete : ");
scanf("%d",&key);
root=DeleteNode(root,key);
}
getch(); break;
case 8: if(root==NULL)
printf("Tree is Empty");
else
{
count=0;
printf("\nNo of node in a binary tree = %d ",CountNodes(root));
}
getch(); break;
case 9: if(root==NULL)
printf("Tree is Empty");
else
printf("\nNo of Leaf node in a binary tree = %d
",CountLeafNodes(root));
getch(); break;
case 10: break;
default:printf("Invalid Choice : ");
}
}while(choice!=10);
getch();
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy