在 C++ 中統計權重為完全平方數的節點
給定一棵二叉樹及其節點的權重。目標是找到權重為完全平方數的節點的數量。如果權重為 36,則它是 6 的平方,因此該節點將被計算在內。
例如
輸入
輸入值後建立的樹如下所示:

輸出
Count the nodes whose weight is a perfect square are: 4
解釋
我們得到了樹的節點以及與每個節點關聯的權重。現在我們檢查節點的數字是否為完全平方數。
| 節點 | 權重 | 完全平方數 | 是/否 |
|---|---|---|---|
| 2 | 121 | 11*11 | 是 |
| 1 | 81 | 9*9 | 是 |
| 4 | 37 | 質數 | 否 |
| 3 | 25 | 5*5 | 是 |
| 8 | 100 | 10*10 | 是 |
| 9 | 701 | 不可能 | 否 |
輸入
輸入值後建立的樹如下所示:

輸出
Count the nodes whose weight is a perfect square are: 2
解釋
we are given with the tree nodes and the weights associated with each node. Now we check whether the digits of nodes are perfect squares or not.
| 節點 | 權重 | 完全平方數 | 是/否 |
|---|---|---|---|
| 2 | 11 | 不可能 | 否 |
| 1 | 16 | 4*4 | 是 |
| 4 | 4 | 2*2 | 是 |
| 3 | 26 | 不可能 | 否 |
| 8 | 1001 | 不可能 | 否 |
**以下程式中使用的方案如下**:
在這種方法中,我們將對樹的圖應用深度優先搜尋 (DFS) 來遍歷它並檢查節點的權重是否為完全平方數。為此,我們將使用兩個向量 Node_Weight(100) 和 edge_graph[100]。
使用節點的權重初始化 Node_Weight[]。
使用向量 edge_graph 建立一棵樹。
取一個全域性變數 square 並將其初始化為 0。
函式 check(int check_it) 獲取一個整數,如果 check_it 是完全平方數,則返回 true。
取 total = sqrt(check_it)
現在,如果 (floor(total) != ceil(total)) 返回 true,則 total 不是完全平方數,返回 false。
否則返回 true。
函式 perfect_square(int node, int root) 獲取樹的節點和根節點,並返回給定樹中權重為完全平方數的節點的數量。
如果 if(check(Node_Weight[node])) 返回 true,則遞增 square。
使用 for 迴圈遍歷向量 edge_graph[node] 中的樹。
對向量中的下一個節點呼叫 perfect_square(it, node)。
在所有函式結束時,我們將得到 square 作為權重值為完全平方數的節點的數量。
示例
#include <bits/stdc++.h>
using namespace std;
vector<int> Node_Weight(100);
vector<int> edge_graph[100];
int square = 0;
bool check(int check_it){
double total = sqrt(check_it);
if(floor(total) != ceil(total)){
return false;
}
return true;
}
void perfect_square(int node, int root){
if(check(Node_Weight[node])){
square++;
}
for (int it : edge_graph[node]){
if(it == root){
continue;
}
perfect_square(it, node);
}
}
int main(){
//weight of the nodes
Node_Weight[2] = 121;
Node_Weight[1] = 81;
Node_Weight[4] = 37;
Node_Weight[3] = 25;
Node_Weight[8] = 100;
Node_Weight[9] = 701;
//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);
perfect_square(2, 2);
cout<<"Count the nodes whose weight is a perfect square are: "<<square;
return 0;
}輸出
如果我們執行以上程式碼,它將生成以下輸出:
Count the nodes whose weight is a perfect square are: 4
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP