Convert a tree to forest of even nodes in C++

In this tutorial, we will be discussing a program to convert a tree to a forest of even nodes.

For this we will be provided with a binary tree of say N nodes. Our task is to calculate the maximum number of edges that can be removed to get forest of even nodes.


 Live Demo

#define N 12
using namespace std;
//returning the number of nodes of subtree
//having the root node
int depth_search(vector<int> tree[N], int visit[N], int *ans, int node){
   int num = 0, temp = 0;
   //marking nodes as visited
   visit[node] = 1;
   for (int i = 0; i < tree[node].size(); i++){
      if (visit[tree[node][i]] == 0){
      //finding total nodes of the sub subtree
      temp = depth_search(tree, visit, ans, tree[node][i]);
      //if nodes are even, increment the edges to be removed by 1
      (temp%2)?(num += temp):((*ans)++);
   return num+1;
//returning the maximum number of edges to be removed
int print_maxedge(vector<int> tree[N], int n){
   int visit[n+2];
   int ans = 0;
   memset(visit, 0, sizeof visit);
   depth_search(tree, visit, &ans, 1);
   return ans;
int main(){
   int n = 10;
   vector<int> tree[n+2];
   cout << print_maxedge(tree, n) << endl;
   return 0;