在 C++ 中将树转换成偶数节点林


在本文中,我们将讨论一个将树转换成偶数节点林的程序。

为此,我们提供一棵 N 个节点的二叉树。我们的任务是计算可以移出以获取偶数节点林的最大边数。

范例

 在线演示

#include<bits/stdc++.h>
#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];
   tree[1].push_back(3);
   tree[3].push_back(1);
   tree[1].push_back(6);
   tree[6].push_back(1);
   tree[1].push_back(2);
   tree[2].push_back(1);
   tree[3].push_back(4);
   tree[4].push_back(3);
   tree[6].push_back(8);
   tree[8].push_back(6);
   tree[2].push_back(7);
   tree[7].push_back(2);
   tree[2].push_back(5);
   tree[5].push_back(2);
   tree[4].push_back(9);
   tree[9].push_back(4);
   tree[4].push_back(10);
   tree[10].push_back(4);
   cout << print_maxedge(tree, n) << endl;
   return 0;
}

输出

2

更新时间:06-Jan-2020

179 浏览量

开启你的职业生涯

完成课程获得认证

开始
广告