用 C++ 打印树中节点数为奇数和偶数的所有层
在这个问题中,我们给定一棵树。我们需要打印所有节点数为偶数和奇数的层。
让我们举个例子来更好地理解这个概念。

输出 -
Levels with odd number of nodes: 1, 3, 4 Levels with even number of nodes: 2
解释 - 第 1 层只有一个元素(奇数),第 2 层包含两个元素(偶数),第 3 层包含 3 个元素(奇数),第 4 层包含 1 个元素(偶数)。
现在,为了解决这个问题,我们需要找到每一层的节点数量,并相应地打印奇偶层。
我们将按照以下步骤找到解决方案 -
步骤 1 - 使用 height[node]=1+height[parent] 对每一层运行搜索算法。
步骤 2 - 对于每一层,存储该层上的节点数量。
步骤 3 - 遍历包含元素的数组,并打印奇偶层。
示例
#include <bits/stdc++.h>
using namespace std;
void traversal(int node, int parent, int height[], int vis[], vector<int> tree[]){
height[node] = 1 + height[parent];
vis[node] = 1;
for (auto it : tree[node]) {
if (!vis[it]) {
traversal(it, node, height, vis, tree);
}
}
}
void insert(int x, int y, vector<int> tree[]){
tree[x].push_back(y);
tree[y].push_back(x);
}
void evenOddLevels(int N, int vis[], int height[]){
int mark[N + 1];
memset(mark, 0, sizeof mark);
int maxLevel = 0;
for (int i = 1; i <= N; i++) {
if (vis[i])
mark[height[i]]++;
maxLevel = max(height[i], maxLevel);
}
cout << "The levels with odd number of nodes are: ";
for (int i = 1; i <= maxLevel; i++) {
if (mark[i] % 2)
cout << i << " ";
}
cout << "\nThe levels with even number of nodes are: ";
for (int i = 1; i <= maxLevel; i++) {
if (mark[i] % 2 == 0)
cout << i << " ";
}
}
int main(){
const int N = 9;
vector<int> tree[N + 1];
insert(1, 2, tree);
insert(1, 3, tree);
insert(2, 4, tree);
insert(2, 5, tree);
insert(5, 7, tree);
insert(5, 8, tree);
insert(3, 6, tree);
insert(6, 9, tree);
int height[N + 1];
int vis[N + 1] = { 0 };
height[0] = 0;
traversal(1, 0, height, vis, tree);
evenOddLevels(N, vis, height);
return 0;
}输出
The levels with odd number of nodes are: 1 3 4 The levels with even number of nodes are: 2
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP