 GeeksforGeeks App
Open App Browser
Continue

# Vertex Cover Problem (Dynamic Programming Solution for Tree)

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 ``#include ` `// 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 ``#include ` `// 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

 ``

Output

`Size 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 ``#include ` `// 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 ``#include ` `// 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

 ``

## 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()`

Output

`Size 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:
http://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 ``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] += dp[child];` `            ``// including source in the vertex cover``            ``dp[src] += min(dp[child], dp[child]);``        ``}``    ``}``}` `// 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, dp) << 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 > adj, ``int` `x,``                        ``int` `y)``    ``{``        ``adj.get(x).add(y);``        ``adj.get(y).add(x);``    ``}` `    ``static` `void` `dfs(List > adj,``                    ``List > 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 > adj,``                                   ``int` `N)``    ``{``        ``List > 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 > 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> adj, ``int` `x, ``int` `y)``    ``{``        ``adj[x].Add(y);``        ``adj[y].Add(x);``    ``}` `    ``static` `void` `dfs(List> adj, List> 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] = dp[child] + dp[src];` `                ``// including source in the vertex cover``                ``dp[src] = dp[src] + Math.Min(dp[child], dp[child]);``            ``}``        ``}``    ``}` `    ``// function to find minimum size of vertex cover``    ``static` `void` `minSizeVertexCover(List> adj, ``int` `N)``    ``{``        ``List> dp = ``new` `List>();``        ``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, dp));``    ``}` `    ``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> adj = ``new` `List>();``        ``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] += dp[child];` `            ``// including source in the vertex cover``            ``dp[src] += Math.min(dp[child], dp[child]);``          ``}``        ``}``      ``}` `      ``// 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, dp));``      ``}` `      ``// 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);`

Output

`3`

Time Complexity : O(N)
Auxiliary space : O(N)

My Personal Notes arrow_drop_up