Vertex Cover Problem (Dynamic Programming Solution for Tree)
Last Updated :
23 Jul, 2025
A vertex cover of an undirected graph is a subset of its vertices such that for every edge (u, v) of the graph, either ‘u’ or ‘v’ is in vertex cover. Although the name is Vertex Cover, the set covers all edges of the given graph.
The problem to find minimum size vertex cover of a graph is NP complete. But it can be solved in polynomial time for trees. In this post a solution for Binary Tree is discussed. The same solution can be extended for n-ary trees.
For example, consider the following binary tree. The smallest vertex cover is {20, 50, 30} and size of the vertex cover is 3.

The idea is to consider following two possibilities for root and recursively for all nodes down the root.
1) Root is part of vertex cover: In this case root covers all children edges. We recursively calculate size of vertex covers for left and right subtrees and add 1 to the result (for root).
2) Root is not part of vertex cover: In this case, both children of root must be included in vertex cover to cover all root to children edges. We recursively calculate size of vertex covers of all grandchildren and number of children to the result (for two children of root).
Below are implementation of above idea.
C
// A naive recursive C implementation for vertex cover problem for a tree
#include <stdio.h>
#include <stdlib.h>
// A utility function to find min of two integers
int min(int x, int y) { return (x < y)? x: y; }
/* A binary tree node has data, pointer to left child and a pointer to
right child */
struct node
{
int data;
struct node *left, *right;
};
// The function returns size of the minimum vertex cover
int vCover(struct node *root)
{
// The size of minimum vertex cover is zero if tree is empty or there
// is only one node
if (root == NULL)
return 0;
if (root->left == NULL && root->right == NULL)
return 0;
// Calculate size of vertex cover when root is part of it
int size_incl = 1 + vCover(root->left) + vCover(root->right);
// Calculate size of vertex cover when root is not part of it
int size_excl = 0;
if (root->left)
size_excl += 1 + vCover(root->left->left) + vCover(root->left->right);
if (root->right)
size_excl += 1 + vCover(root->right->left) + vCover(root->right->right);
// Return the minimum of two sizes
return min(size_incl, size_excl);
}
// A utility function to create a node
struct node* newNode( int data )
{
struct node* temp = (struct node *) malloc( sizeof(struct node) );
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// Driver program to test above functions
int main()
{
// Let us construct the tree given in the above diagram
struct node *root = newNode(20);
root->left = newNode(8);
root->left->left = newNode(4);
root->left->right = newNode(12);
root->left->right->left = newNode(10);
root->left->right->right = newNode(14);
root->right = newNode(22);
root->right->right = newNode(25);
printf ("Size of the smallest vertex cover is %d ", vCover(root));
return 0;
}
C++
#include <iostream>
#include <cstdlib>
// A utility function to find min of two integers
int min(int x, int y) { return (x < y)? x: y; }
/* A binary tree node has data, pointer to left child and a pointer to
right child */
struct node
{
int data;
node *left, *right;
};
// The function returns size of the minimum vertex cover
int vCover(node *root)
{
// The size of minimum vertex cover is zero if tree is empty or there
// is only one node
if (root == nullptr)
return 0;
if (root->left == nullptr && root->right == nullptr)
return 0;
// Calculate size of vertex cover when root is part of it
int size_incl = 1 + vCover(root->left) + vCover(root->right);
// Calculate size of vertex cover when root is not part of it
int size_excl = 0;
if (root->left)
size_excl += 1 + vCover(root->left->left) + vCover(root->left->right);
if (root->right)
size_excl += 1 + vCover(root->right->left) + vCover(root->right->right);
// Return the minimum of two sizes
return min(size_incl, size_excl);
}
// A utility function to create a node
node* newNode( int data )
{
node* temp = new node;
temp->data = data;
temp->left = temp->right = nullptr;
return temp;
}
// Driver program to test above functions
int main()
{
// Let us construct the tree given in the above diagram
node *root = newNode(20);
root->left = newNode(8);
root->left->left = newNode(4);
root->left->right = newNode(12);
root->left->right->left = newNode(10);
root->left->right->right = newNode(14);
root->right = newNode(22);
root->right->right = newNode(25);
std::cout << "Size of the smallest vertex cover is " << vCover(root) << std::endl;
return 0;
}
Java
// A naive recursive Java implementation
// for vertex cover problem for a tree
class GFG
{
// A utility function to find min of two integers
static int min(int x, int y)
{
return (x < y) ? x : y;
}
/*
* A binary tree node has data, pointer
to left child and a pointer to right
* child
*/
static class node
{
int data;
node left, right;
};
// The function returns size
// of the minimum vertex cover
static int vCover(node root)
{
// The size of minimum vertex cover
// is zero if tree is empty or there
// is only one node
if (root == null)
return 0;
if (root.left == null && root.right == null)
return 0;
// Calculate size of vertex cover
// when root is part of it
int size_incl = 1 + vCover(root.left) +
vCover(root.right);
// Calculate size of vertex cover
// when root is not part of it
int size_excl = 0;
if (root.left != null)
size_excl += 1 + vCover(root.left.left) +
vCover(root.left.right);
if (root.right != null)
size_excl += 1 + vCover(root.right.left) +
vCover(root.right.right);
// Return the minimum of two sizes
return Math.min(size_incl, size_excl);
}
// A utility function to create a node
static node newNode(int data)
{
node temp = new node();
temp.data = data;
temp.left = temp.right = null;
return temp;
}
// Driver code
public static void main(String[] args)
{
// Let us construct tree given in the above diagram
node root = newNode(20);
root.left = newNode(8);
root.left.left = newNode(4);
root.left.right = newNode(12);
root.left.right.left = newNode(10);
root.left.right.right = newNode(14);
root.right = newNode(22);
root.right.right = newNode(25);
System.out.printf("Size of the smallest vertex" +
"cover is %d ", vCover(root));
}
}
// This code is contributed by 29AjayKumar
Python3
# A naive recursive Python3 implementation
# for vertex cover problem for a tree
# A utility function to find min of two integers
# A binary tree node has data, pointer to
# left child and a pointer to right child
class Node:
def __init__(self, x):
self.data = x
self.left = None
self.right = None
# The function returns size of
# the minimum vertex cover
def vCover(root):
# The size of minimum vertex cover
# is zero if tree is empty or there
# is only one node
if (root == None):
return 0
if (root.left == None and
root.right == None):
return 0
# Calculate size of vertex cover when
# root is part of it
size_incl = (1 + vCover(root.left) +
vCover(root.right))
# Calculate size of vertex cover
# when root is not part of it
size_excl = 0
if (root.left):
size_excl += (1 + vCover(root.left.left) +
vCover(root.left.right))
if (root.right):
size_excl += (1 + vCover(root.right.left) +
vCover(root.right.right))
# Return the minimum of two sizes
return min(size_incl, size_excl)
# Driver Code
if __name__ == '__main__':
# Let us construct the tree
# given in the above diagram
root = Node(20)
root.left = Node(8)
root.left.left = Node(4)
root.left.right = Node(12)
root.left.right.left = Node(10)
root.left.right.right = Node(14)
root.right = Node(22)
root.right.right = Node(25)
print("Size of the smallest vertex cover is", vCover(root))
# This code is contributed by mohit kumar 29
C#
// A naive recursive C# implementation
// for vertex cover problem for a tree
using System;
class GFG
{
// A utility function to find
// min of two integers
static int min(int x, int y)
{
return (x < y) ? x : y;
}
/*
* A binary tree node has data, pointer
to left child and a pointer to right
* child
*/
public class node
{
public int data;
public node left, right;
};
// The function returns size
// of the minimum vertex cover
static int vCover(node root)
{
// The size of minimum vertex cover
// is zero if tree is empty or there
// is only one node
if (root == null)
return 0;
if (root.left == null &&
root.right == null)
return 0;
// Calculate size of vertex cover
// when root is part of it
int size_incl = 1 + vCover(root.left) +
vCover(root.right);
// Calculate size of vertex cover
// when root is not part of it
int size_excl = 0;
if (root.left != null)
size_excl += 1 + vCover(root.left.left) +
vCover(root.left.right);
if (root.right != null)
size_excl += 1 + vCover(root.right.left) +
vCover(root.right.right);
// Return the minimum of two sizes
return Math.Min(size_incl, size_excl);
}
// A utility function to create a node
static node newNode(int data)
{
node temp = new node();
temp.data = data;
temp.left = temp.right = null;
return temp;
}
// Driver code
public static void Main(String[] args)
{
// Let us construct tree given
// in the above diagram
node root = newNode(20);
root.left = newNode(8);
root.left.left = newNode(4);
root.left.right = newNode(12);
root.left.right.left = newNode(10);
root.left.right.right = newNode(14);
root.right = newNode(22);
root.right.right = newNode(25);
Console.Write("Size of the smallest vertex" +
"cover is {0} ", vCover(root));
}
}
// This code is contributed by 29AjayKumar
JavaScript
<script>
// A naive recursive Javascript implementation
// for vertex cover problem for a tree
// A utility function to find min of two integers
function min(x,y)
{
return (x < y) ? x : y;
}
/*
* A binary tree node has data, pointer
to left child and a pointer to right
* child
*/
class Node
{
constructor(d)
{
this.data=d;
this.left=null;
this.right=null;
}
}
// The function returns size
// of the minimum vertex cover
function vCover(root)
{
// The size of minimum vertex cover
// is zero if tree is empty or there
// is only one node
if (root == null)
return 0;
if (root.left == null && root.right == null)
return 0;
// Calculate size of vertex cover
// when root is part of it
let size_incl = 1 + vCover(root.left) +
vCover(root.right);
// Calculate size of vertex cover
// when root is not part of it
let size_excl = 0;
if (root.left != null)
size_excl += 1 + vCover(root.left.left) +
vCover(root.left.right);
if (root.right != null)
size_excl += 1 + vCover(root.right.left) +
vCover(root.right.right);
// Return the minimum of two sizes
return Math.min(size_incl, size_excl);
}
// Driver code
// Let us construct tree given in the above diagram
root = new Node(20);
root.left = new Node(8);
root.left.left = new Node(4);
root.left.right = new Node(12);
root.left.right.left = new Node(10);
root.left.right.right = new Node(14);
root.right = new Node(22);
root.right.right = new Node(25);
document.write("Size of the smallest vertex" +
"cover is ", vCover(root));
// This code is contributed by unknown2108
</script>
OutputSize of the smallest vertex cover is 3
Time complexity of the above naive recursive approach is exponential. It should be noted that the above function computes the same subproblems again and again. For example, vCover of node with value 50 is evaluated twice as 50 is grandchild of 10 and child of 20.
Since same subproblems are called again, this problem has Overlapping Subproblems property. So Vertex Cover problem has both properties (see this and this) of a dynamic programming problem. Like other typical Dynamic Programming(DP) problems, re-computations of same subproblems can be avoided by storing the solutions to subproblems and solving problems in bottom up manner.
Following is the implementation of Dynamic Programming based solution. In the following solution, an additional field ‘vc’ is added to tree nodes. The initial value of ‘vc’ is set as 0 for all nodes. The recursive function vCover() calculates ‘vc’ for a node only if it is not already set.
C
/* Dynamic programming based program for Vertex Cover problem for
a Binary Tree */
#include <stdio.h>
#include <stdlib.h>
// A utility function to find min of two integers
int min(int x, int y) { return (x < y)? x: y; }
/* A binary tree node has data, pointer to left child and a pointer to
right child */
struct node
{
int data;
int vc;
struct node *left, *right;
};
// A memoization based function that returns size of the minimum vertex cover.
int vCover(struct node *root)
{
// The size of minimum vertex cover is zero if tree is empty or there
// is only one node
if (root == NULL)
return 0;
if (root->left == NULL && root->right == NULL)
return 0;
// If vertex cover for this node is already evaluated, then return it
// to save recomputation of same subproblem again.
if (root->vc != 0)
return root->vc;
// Calculate size of vertex cover when root is part of it
int size_incl = 1 + vCover(root->left) + vCover(root->right);
// Calculate size of vertex cover when root is not part of it
int size_excl = 0;
if (root->left)
size_excl += 1 + vCover(root->left->left) + vCover(root->left->right);
if (root->right)
size_excl += 1 + vCover(root->right->left) + vCover(root->right->right);
// Minimum of two values is vertex cover, store it before returning
root->vc = min(size_incl, size_excl);
return root->vc;
}
// A utility function to create a node
struct node* newNode( int data )
{
struct node* temp = (struct node *) malloc( sizeof(struct node) );
temp->data = data;
temp->left = temp->right = NULL;
temp->vc = 0; // Set the vertex cover as 0
return temp;
}
// Driver program to test above functions
int main()
{
// Let us construct the tree given in the above diagram
struct node *root = newNode(20);
root->left = newNode(8);
root->left->left = newNode(4);
root->left->right = newNode(12);
root->left->right->left = newNode(10);
root->left->right->right = newNode(14);
root->right = newNode(22);
root->right->right = newNode(25);
printf ("Size of the smallest vertex cover is %d ", vCover(root));
return 0;
}
C++
#include <iostream>
#include <stdlib.h>
// A utility function to find min of two integers
int min(int x, int y) { return (x < y)? x: y; }
/* A binary tree node has data, pointer to left child and a pointer to
right child */
struct node
{
int data;
int vc;
struct node *left, *right;
};
// A memoization based function that returns size of the minimum vertex cover.
int vCover(struct node *root)
{
// The size of minimum vertex cover is zero if tree is empty or there
// is only one node
if (root == NULL)
return 0;
if (root->left == NULL && root->right == NULL)
return 0;
// If vertex cover for this node is already evaluated, then return it
// to save recomputation of same subproblem again.
if (root->vc != 0)
return root->vc;
// Calculate size of vertex cover when root is part of it
int size_incl = 1 + vCover(root->left) + vCover(root->right);
// Calculate size of vertex cover when root is not part of it
int size_excl = 0;
if (root->left)
size_excl += 1 + vCover(root->left->left) + vCover(root->left->right);
if (root->right)
size_excl += 1 + vCover(root->right->left) + vCover(root->right->right);
// Minimum of two values is vertex cover, store it before returning
root->vc = min(size_incl, size_excl);
return root->vc;
}
// A utility function to create a node
struct node* newNode( int data )
{
struct node* temp = (struct node *) malloc( sizeof(struct node) );
temp->data = data;
temp->left = temp->right = NULL;
temp->vc = 0; // Set the vertex cover as 0
return temp;
}
// Driver program to test above functions
int main()
{
// Let us construct the tree given in the above diagram
struct node *root = newNode(20);
root->left = newNode(8);
root->left->left = newNode(4);
root->left->right = newNode(12);
root->left->right->left = newNode(10);
root->left->right->right = newNode(14);
root->right = newNode(22);
root->right->right = newNode(25);
std::cout << "Size of the smallest vertex cover is " << vCover(root) << std::endl;
return 0;
}
Java
/* Dynamic programming based program for
Vertex Cover problem for a Binary Tree */
class GFG
{
// A utility function to find min of two integers
static int min(int x, int y)
{
return (x < y) ? x : y;
}
/*
* A binary tree node has data, pointer
to left child and a pointer to right
* child
*/
static class node
{
int data;
int vc;
node left, right;
};
// A memoization based function that returns
// size of the minimum vertex cover.
static int vCover(node root)
{
// The size of minimum vertex cover is zero
// if tree is empty or there is only one node
if (root == null)
return 0;
if (root.left == null && root.right == null)
return 0;
// If vertex cover for this node is
// already evaluated, then return it
// to save recomputation of same subproblem again.
if (root.vc != 0)
return root.vc;
// Calculate size of vertex cover
// when root is part of it
int size_incl = 1 + vCover(root.left) +
vCover(root.right);
// Calculate size of vertex cover
// when root is not part of it
int size_excl = 0;
if (root.left != null)
size_excl += 1 + vCover(root.left.left) +
vCover(root.left.right);
if (root.right != null)
size_excl += 1 + vCover(root.right.left) +
vCover(root.right.right);
// Minimum of two values is vertex cover,
// store it before returning
root.vc = Math.min(size_incl, size_excl);
return root.vc;
}
// A utility function to create a node
static node newNode(int data)
{
node temp = new node();
temp.data = data;
temp.left = temp.right = null;
temp.vc = 0; // Set the vertex cover as 0
return temp;
}
// Driver code
public static void main(String[] args)
{
// Let us construct tree given in the above diagram
node root = newNode(20);
root.left = newNode(8);
root.left.left = newNode(4);
root.left.right = newNode(12);
root.left.right.left = newNode(10);
root.left.right.right = newNode(14);
root.right = newNode(22);
root.right.right = newNode(25);
System.out.printf("Size of the smallest vertex" +
"cover is %d ", vCover(root));
}
}
// This code is contributed by PrinciRaj1992
C#
/* Dynamic programming based program for
Vertex Cover problem for a Binary Tree */
using System;
class GFG
{
// A utility function to find
// min of two integers
static int min(int x, int y)
{
return (x < y) ? x : y;
}
/*
* A binary tree node has data, pointer
to left child and a pointer to right
* child
*/
class node
{
public int data;
public int vc;
public node left, right;
};
// A memoization based function that returns
// size of the minimum vertex cover.
static int vCover(node root)
{
// The size of minimum vertex cover is zero
// if tree is empty or there is only one node
if (root == null)
return 0;
if (root.left == null &&
root.right == null)
return 0;
// If vertex cover for this node is
// already evaluated, then return it
// to save recomputation of same subproblem again.
if (root.vc != 0)
return root.vc;
// Calculate size of vertex cover
// when root is part of it
int size_incl = 1 + vCover(root.left) +
vCover(root.right);
// Calculate size of vertex cover
// when root is not part of it
int size_excl = 0;
if (root.left != null)
size_excl += 1 + vCover(root.left.left) +
vCover(root.left.right);
if (root.right != null)
size_excl += 1 + vCover(root.right.left) +
vCover(root.right.right);
// Minimum of two values is vertex cover,
// store it before returning
root.vc = Math.Min(size_incl, size_excl);
return root.vc;
}
// A utility function to create a node
static node newNode(int data)
{
node temp = new node();
temp.data = data;
temp.left = temp.right = null;
temp.vc = 0; // Set the vertex cover as 0
return temp;
}
// Driver code
public static void Main(String[] args)
{
// Let us construct tree given in the above diagram
node root = newNode(20);
root.left = newNode(8);
root.left.left = newNode(4);
root.left.right = newNode(12);
root.left.right.left = newNode(10);
root.left.right.right = newNode(14);
root.right = newNode(22);
root.right.right = newNode(25);
Console.Write("Size of the smallest vertex" +
"cover is {0} ", vCover(root));
}
}
// This code is contributed by PrinciRaj1992
JavaScript
<script>
/* Dynamic programming based program for
Vertex Cover problem for a Binary Tree */
// A utility function to find min of two integers
function min(x,y)
{
return (x < y) ? x : y;
}
/*
* A binary tree node has data, pointer
to left child and a pointer to right
* child
*/
class Node
{
constructor(data)
{
this.vc=0;
this.data=data;
this.left=this.right=null;
}
}
// A memoization based function that returns
// size of the minimum vertex cover.
function vCover(root)
{
// The size of minimum vertex cover is zero
// if tree is empty or there is only one node
if (root == null)
return 0;
if (root.left == null && root.right == null)
return 0;
// If vertex cover for this node is
// already evaluated, then return it
// to save recomputation of same subproblem again.
if (root.vc != 0)
return root.vc;
// Calculate size of vertex cover
// when root is part of it
let size_incl = 1 + vCover(root.left) +
vCover(root.right);
// Calculate size of vertex cover
// when root is not part of it
let size_excl = 0;
if (root.left != null)
size_excl += 1 + vCover(root.left.left) +
vCover(root.left.right);
if (root.right != null)
size_excl += 1 + vCover(root.right.left) +
vCover(root.right.right);
// Minimum of two values is vertex cover,
// store it before returning
root.vc = Math.min(size_incl, size_excl);
return root.vc;
}
// Driver code
// Let us construct tree given in the above diagram
let root = new Node(20);
root.left = new Node(8);
root.left.left = new Node(4);
root.left.right = new Node(12);
root.left.right.left = new Node(10);
root.left.right.right = new Node(14);
root.right = new Node(22);
root.right.right = new Node(25);
document.write("Size of the smallest vertex " +
"cover is ", vCover(root));
// This code is contributed by rag2127
</script>
Python3
# A binary tree node has data, pointer to left child and a pointer to
# right child
class node:
def __init__(self):
# instance fields found by C++ to Python Converter:
self.data = 0
self.vc = 0
self.left = None
self.right = None
# Driver program to test above functions
def main():
# Let us construct the tree given in the above diagram
root = Globals.newNode(20)
root.left = Globals.newNode(8)
root.left.left = Globals.newNode(4)
root.left.right = Globals.newNode(12)
root.left.right.left = Globals.newNode(10)
root.left.right.right = Globals.newNode(14)
root.right = Globals.newNode(22)
root.right.right = Globals.newNode(25)
print("Size of the smallest vertex cover is ", end='')
print(Globals.vCover(root), end='')
print("\n", end='')
class Globals:
# A utility function to find min of two integers
@staticmethod
def min(x, y):
if(x < y):
return x
else:
return y
# A memoization based function that returns size of the minimum vertex cover.
@staticmethod
def vCover(root):
# The size of minimum vertex cover is zero if tree is empty or there
# is only one node
if root is None:
return 0
if root.left is None and root.right is None:
return 0
# If vertex cover for this node is already evaluated, then return it
# to save recomputation of same subproblem again.
if root.vc != 0:
return root.vc
# Calculate size of vertex cover when root is part of it
size_incl = 1 + Globals.vCover(root.left) + Globals.vCover(root.right)
# Calculate size of vertex cover when root is not part of it
size_excl = 0
if root.left:
size_excl += 1 + \
Globals.vCover(root.left.left) + \
Globals.vCover(root.left.right)
if root.right:
size_excl += 1 + \
Globals.vCover(root.right.left) + \
Globals.vCover(root.right.right)
# Minimum of two values is vertex cover, store it before returning
root.vc = Globals.min(size_incl, size_excl)
return root.vc
# A utility function to create a node
@staticmethod
def newNode(data):
temp = node()
temp.data = data
temp.left = temp.right = None
temp.vc = 0 # Set the vertex cover as 0
return temp
if __name__ == "__main__":
main()
OutputSize of the smallest vertex cover is 3
Time Complexity:
The time complexity of the vCover function is O(n), where n is the number of nodes in the binary tree. This is because each node is visited only once and its vertex cover size is calculated in constant time.
Space Complexity:
The space complexity of the program is O(n), where n is the number of nodes in the binary tree. This is because the space required for the binary tree is proportional to the number of nodes in the tree. Additionally, the memoization technique used in the vCover function requires additional space to store the vertex cover sizes of already evaluated nodes. However, since the depth of the recursion tree is limited by the height of the binary tree, the space complexity of the program is also O(h), where h is the height of the binary tree. In the worst case scenario where the binary tree is skewed, the height of the tree can be as large as n, which would result in a space complexity of O(n).
References:
https://courses.csail.mit.edu/6.006/spring11/lectures/lec21.pdf
Exercise:
Extend the above solution for n-ary trees.
Approach for any general tree :
1. Approach will be same dynamic programming approach as discussed.
2. For every node, if we exclude this node from vertex cover than we have to include its neighbouring nodes,
and if we include this node in the vertex cover than we will take the minimum of the two possibilities of taking its neighbouring
nodes in the vertex cover to get minimum vertex cover.
3. We will store the above information in the dp array.
C++
// C++ implementation for the above approach
#include <bits/stdc++.h>
using namespace std;
// An utility function to add an edge in the tree
void addEdge(vector<int> adj[], int x, int y)
{
adj[x].push_back(y);
adj[y].push_back(x);
}
void dfs(vector<int> adj[], vector<int> dp[], int src,
int par)
{
for (auto child : adj[src]) {
if (child != par)
dfs(adj, dp, child, src);
}
for (auto child : adj[src]) {
if (child != par) {
// not including source in the vertex cover
dp[src][0] += dp[child][1];
// including source in the vertex cover
dp[src][1] += min(dp[child][1], dp[child][0]);
}
}
}
// function to find minimum size of vertex cover
void minSizeVertexCover(vector<int> adj[], int N)
{
vector<int> dp[N + 1];
for (int i = 1; i <= N; i++) {
// 0 denotes not included in vertex cover
dp[i].push_back(0);
// 1 denotes included in vertex cover
dp[i].push_back(1);
}
dfs(adj, dp, 1, -1);
// printing minimum size vertex cover
cout << min(dp[1][0], dp[1][1]) << endl;
}
// Driver Code
int main()
{
/* 1
/ \
2 7
/ \
3 6
/ | \
4 8 5
*/
// number of nodes in the tree
int N = 8;
// adjacency list representation of the tree
vector<int> adj[N + 1];
addEdge(adj, 1, 2);
addEdge(adj, 1, 7);
addEdge(adj, 2, 3);
addEdge(adj, 2, 6);
addEdge(adj, 3, 4);
addEdge(adj, 3, 8);
addEdge(adj, 3, 5);
minSizeVertexCover(adj, N);
return 0;
}
Java
// Java implementation for the above approach
import java.util.*;
class GFG {
// An utility function to add an edge in the tree
static void addEdge(List<List<Integer> > adj, int x,
int y)
{
adj.get(x).add(y);
adj.get(y).add(x);
}
static void dfs(List<List<Integer> > adj,
List<List<Integer> > dp, int src,
int par)
{
for (Integer child : adj.get(src)) {
if (child != par)
dfs(adj, dp, child, src);
}
for (Integer child : adj.get(src)) {
if (child != par) {
// not including source in the vertex cover
dp.get(src).set(0,
dp.get(child).get(1)
+ dp.get(src).get(0));
// including source in the vertex cover
dp.get(src).set(
1,
dp.get(src).get(1)
+ Math.min(dp.get(child).get(1),
dp.get(child).get(0)));
}
}
}
// function to find minimum size of vertex cover
static void minSizeVertexCover(List<List<Integer> > adj,
int N)
{
List<List<Integer> > dp = new ArrayList<>();
for (int i = 0; i <= N; i++) {
dp.add(new ArrayList<>());
}
for (int i = 1; i <= N; i++) {
// 0 denotes not included in vertex cover
dp.get(i).add(0);
// 1 denotes included in vertex cover
dp.get(i).add(1);
}
dfs(adj, dp, 1, -1);
// printing minimum size vertex cover
System.out.println(
Math.min(dp.get(1).get(0), dp.get(1).get(1)));
}
public static void main(String[] args)
{
/* 1
/ \
2 7
/ \
3 6
/ | \
4 8 5
*/
// number of nodes in the tree
int N = 8;
// adjacency list representation of the tree
List<List<Integer> > adj = new ArrayList<>();
for (int i = 0; i <= N; i++) {
adj.add(new ArrayList<>());
}
addEdge(adj, 1, 2);
addEdge(adj, 1, 7);
addEdge(adj, 2, 3);
addEdge(adj, 2, 6);
addEdge(adj, 3, 4);
addEdge(adj, 3, 8);
addEdge(adj, 3, 5);
minSizeVertexCover(adj, N);
}
}
Python3
# Python3 implementation for the above approach
def addEdge(adj, x, y):
adj[x].append(y)
adj[y].append(x)
def dfs(adj, dp, src, par):
for child in adj[src]:
if child != par:
dfs(adj, dp, child, src)
for child in adj[src]:
if child != par:
# not including source in the vertex cover
dp[src][0] = dp[child][1] + dp[src][0]
# including source in the vertex cover
dp[src][1] = dp[src][1] + min(dp[child][1], dp[child][0])
def minSizeVertexCover(adj, N):
dp = [[0 for j in range(2)] for i in range(N+1)]
for i in range(1, N+1):
# 0 denotes not included in vertex cover
dp[i][0] = 0
# 1 denotes included in vertex cover
dp[i][1] = 1
dfs(adj, dp, 1, -1)
# printing minimum size vertex cover
print(min(dp[1][0], dp[1][1]))
# Driver Code
"""
1
/ \
2 7
/ \
3 6
/|\
4 8 5
"""
# number of nodes in the tree
N = 8
# adjacency list representation of the tree
adj = [[] for i in range(N+1)]
addEdge(adj, 1, 2)
addEdge(adj, 1, 7)
addEdge(adj, 2, 3)
addEdge(adj, 2, 6)
addEdge(adj, 3, 4)
addEdge(adj, 3, 8)
addEdge(adj, 3, 5)
minSizeVertexCover(adj, N)
C#
using System;
using System.Collections.Generic;
class GFG
{
// An utility function to add an edge in the tree
static void addEdge(List<List<int>> adj, int x, int y)
{
adj[x].Add(y);
adj[y].Add(x);
}
static void dfs(List<List<int>> adj, List<List<int>> dp, int src, int par)
{
foreach (int child in adj[src])
{
if (child != par)
dfs(adj, dp, child, src);
}
foreach (int child in adj[src])
{
if (child != par)
{
// not including source in the vertex cover
dp[src][0] = dp[child][1] + dp[src][0];
// including source in the vertex cover
dp[src][1] = dp[src][1] + Math.Min(dp[child][1], dp[child][0]);
}
}
}
// function to find minimum size of vertex cover
static void minSizeVertexCover(List<List<int>> adj, int N)
{
List<List<int>> dp = new List<List<int>>();
for (int i = 0; i <= N; i++)
{
dp.Add(new List<int>());
}
for (int i = 1; i <= N; i++)
{
// 0 denotes not included in vertex cover
dp[i].Add(0);
// 1 denotes included in vertex cover
dp[i].Add(1);
}
dfs(adj, dp, 1, -1);
// printing minimum size vertex cover
Console.WriteLine(Math.Min(dp[1][0], dp[1][1]));
}
public static void Main(string[] args)
{
/*
1
/ \
2 7
/ \
3 6
/ | \
4 8 5
*/
// number of nodes in the tree
int N = 8;
// adjacency list representation of the tree
List<List<int>> adj = new List<List<int>>();
for (int i = 0; i <= N; i++)
{
adj.Add(new List<int>());
}
addEdge(adj, 1, 2);
addEdge(adj, 1, 7);
addEdge(adj, 2, 3);
addEdge(adj, 2, 6);
addEdge(adj, 3, 4);
addEdge(adj, 3, 8);
addEdge(adj, 3, 5);
minSizeVertexCover(adj, N);
}
}
JavaScript
// Javascript implementation for the above approach
// An utility function to add an edge in the tree
function addEdge(adj, x, y) {
adj[x].push(y);
adj[y].push(x);
}
function dfs(adj, dp, src, par) {
for (let child of adj[src]) {
if (child != par) dfs(adj, dp, child, src);
}
for (let child of adj[src]) {
if (child != par) {
// not including source in the vertex cover
dp[src][0] += dp[child][1];
// including source in the vertex cover
dp[src][1] += Math.min(dp[child][1], dp[child][0]);
}
}
}
// function to find minimum size of vertex cover
function minSizeVertexCover(adj, N) {
let dp = Array.from(Array(N + 1), () => new Array());
for (var i = 1; i <= N; i++) {
// 0 denotes not included in vertex cover
dp[i].push(0);
// 1 denotes included in vertex cover
dp[i].push(1);
}
dfs(adj, dp, 1, -1);
// printing minimum size vertex cover
console.log(Math.min(dp[1][0], dp[1][1]));
}
// Driver Code
/* 1
/ \
2 7
/ \
3 6
/ | \
4 8 5
*/
// number of nodes in the tree
var N = 8;
// adjacency list representation of the tree
let adj = Array.from(Array(N + 1), () => new Array());
addEdge(adj, 1, 2);
addEdge(adj, 1, 7);
addEdge(adj, 2, 3);
addEdge(adj, 2, 6);
addEdge(adj, 3, 4);
addEdge(adj, 3, 8);
addEdge(adj, 3, 5);
minSizeVertexCover(adj, N);
Time Complexity : O(N)
Auxiliary space : O(N)
Vertex Cover | DSA Problem
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem