用C++统计树中权重字符串包含元音的节点数
给定一棵二叉树,其节点权重为字符串。目标是找到权重字符串包含元音的节点数。如果权重是“aer”,则它包含元音“a”和“e”,因此将计算该节点。
例如
输入
输入值后创建的树如下所示:

输出
Count the nodes of the tree whose weighted string contains a vowel are: 5
解释
我们得到了树节点以及与每个节点关联的字符串权重。现在我们检查节点的字符串是否包含元音。
| 节点 | 权重 | 元音 | 是/否 |
|---|---|---|---|
| 2 | ae | e | 是 |
| 1 | bcd | 无元音 | 否 |
| 4 | io | i,o | 是 |
| 3 | gfe | e | 是 |
| 8 | tptpa | a | 是 |
| 9 | iou | i,o,u | 是 |
输入
输入值后创建的树如下所示:

输出
Count the nodes of the tree whose weighted string contains a vowel are: 3
解释
with the tree nodes and the string weights associated with each node. Now we check whether the string of nodes contains vowels or not.
| 节点 | 权重 | 元音 | 是/否 |
|---|---|---|---|
| 2 | oaei | o,a,e,i | 是 |
| 1 | abcd | 无元音 | 否 |
| 4 | iio | i,o | 是 |
| 3 | ggff | 无元音 | 否 |
| 8 | aaa | a | 是 |
以下程序中使用的方案如下:
在这种方法中,我们将对树的图应用深度优先搜索 (DFS) 来遍历它并检查节点的权重是否包含元音作为字符。为此,请使用两个向量 Node_Weight(100) 和 edge_graph[100]。
用节点的权重初始化 Node_Weight[]。
使用向量 edge_graph 创建树。
取一个全局变量 vowel 并将其初始化为 0。
函数 check(string check_it) 获取一个字符串,如果 check_it 包含元音,则返回 true。
将 length = check_it.length() 作为 check_it 中字符的数量。
使用 for 循环从索引 i=0 到 i<length 遍历 check_it。
将每个 check_it[i] 转换为小写并存储在 c 中。
如果 c 等于任何元音('a'、'e'、'i'、'o'、'u'),则返回 true,否则返回 false。
函数 string_vowel(int node, int root) 获取树的节点和根节点,并返回给定树中权重包含元音作为字符的节点数。
取 str = Node_Weight[node]。
如果 check(str) 返回 true,则递增 vowel。
使用 for 循环遍历向量 edge_graph[node] 中的树。
为向量中的下一个节点调用 string_vowel(it, node)。
在所有函数结束时,我们将 vowel 作为具有元音的权重的节点数。
示例
#include <bits/stdc++.h>
using namespace std;
vector<string> Node_Weight(100);
vector<int> edge_graph[100];
int vowel = 0;
bool check(string check_it){
int length = check_it.length();
for(int i = 0; i <length; i++){
char c = tolower(check_it[i]);
if(c == 'a' ||c == 'e' ||c == 'i' ||c == 'o' ||c == 'u'){
return true;
}
}
return false;
}
void string_vowel(int node, int root){
string str = Node_Weight[node];
if(check(str)){
vowel++;
}
for (int it : edge_graph[node]){
if(it == root){
continue;
}
string_vowel(it, node);
}
}
int main(){
//weight of the nodes
Node_Weight[2] = "ae";
Node_Weight[1] = "bcd";
Node_Weight[4] = "io";
Node_Weight[3] = "gfe";
Node_Weight[8] = "tptpa";
Node_Weight[9] = "iou";
//create graph edge
edge_graph[2].push_back(1);
edge_graph[2].push_back(4);
edge_graph[4].push_back(3);
edge_graph[4].push_back(8);
edge_graph[8].push_back(9);
string_vowel(2, 2);
cout<<"Count the nodes of the tree whose weighted string contains a vowel are: "<<vowel;
return 0;
}输出
如果我们运行上面的代码,它将生成以下输出:
Count the nodes of the tree whose weighted string contains a vowel are: 5
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP