用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