-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtree.cpp
66 lines (56 loc) · 2.02 KB
/
tree.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/* Dynamic programming based solution for Vertex Cover problem for a Binary Tree */
#include <iostream>
#include <cstdlib>
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;
node(int data) : data(data),vc(-1),left(NULL),right(NULL){}
};
// A dynamic programmic based solution that returns size of the minimum vertex cover.
int vertexCover(struct node *root)
{
// The size of minimum vertex cover is zero if tree is empty or there is only one node i.e. root.
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 != -1)
return root->vc;
// Calculate size of vertex cover when root is part of it
int size_root_inc = 1 + vertexCover(root->left) + vertexCover(root->right);
// Calculate size of vertex cover when root is not part of it
int size_root_exc = 0;
if (root->left)
size_root_exc += 1 + vertexCover(root->left->left) + vertexCover(root->left->right);
if (root->right)
size_root_exc += 1 + vertexCover(root->right->left) + vertexCover(root->right->right);
// Minimum of two values is vertex cover, store it before returning.
root->vc = min(size_root_inc, size_root_exc);
// returning minimum of the two.
return root->vc;
}
struct node *newNode(int data)
{
struct node *temp = new node(data);
return temp;
};
int main()
{
struct node *root = newNode(20);
root->left = newNode(18);
root->left->left = newNode(40);
root->left->right = newNode(12);
root->left->right->left = newNode(10);
root->left->right->right = newNode(14);
root->right = newNode(24);
root->right->right = newNode(25);
std::cout << "Size of the minimum vertex cover is " << vertexCover(root);
return 0;
}