C++ 中 n 元树中每个结点的子树中叶结点的数量
在本教程中,我们将编写一个程序,找到 n 元树中每个结点的叶结点数量。
给定一个 n 元树,我们必须找到每个子树的叶结点数量。我们来看一个例子。
输入
N = 8 tree = [[2, 3], [], [4, 5, 6], [7, 8], [], [], [], []]
输出
1->5 2->1 3->4 4->2 5->1 6->1 7->1 8->1
算法
用你喜欢的树初始化 n 元树。
使用 DFS 遍历这棵树。
维护一个数组来存储每个结点叶结点数量的计数。
在对 DFS 进行递归调用后增加叶结点的计数。
打印出具有叶结点数量的所有结点。
实现
以下是上述算法在 C++ 中的实现
#include <bits/stdc++.h>
using namespace std;
void insertNode(int x, int y, vector<int> tree[]) {
tree[x].push_back(y);
}
void DFS(int node, int leaf[], int visited[], vector<int> tree[]) {
leaf[node] = 0;
visited[node] = 1;
for (auto it : tree[node]) {
if (!visited[it]) {
DFS(it, leaf, visited, tree);
leaf[node] += leaf[it];
}
}
if (!tree[node].size()) {
leaf[node] = 1;
}
}
int main() {
int N = 8;
vector<int> tree[N + 1];
insertNode(1, 2, tree);
insertNode(1, 3, tree);
insertNode(3, 4, tree);
insertNode(3, 5, tree);
insertNode(3, 6, tree);
insertNode(4, 7, tree);
insertNode(4, 8, tree);
int leaf[N + 1];
int visited[N + 1];
for (int i = 0; i <= N; i++) {
visited[i] = 0;
}
DFS(1, leaf, visited, tree);
for (int i = 1; i <= N; i++) {
cout << i << "->" << leaf[i] << endl;
}
return 0;
}输出
如果你运行上述代码,那么你将得到以下结果。
1->5 2->1 3->4 4->2 5->1 6->1 7->1 8->1
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言
C++
C#
MongoDB
MySQL
Javascript
PHP