質問
ソースコード全文という項目は、
「全てのノードが5つ子を持つ,深さが4である木構造を考えます.
Initialize関数で,すべてのノードの変数valueに,0~9までの一様乱数を代入します.
(ここまでが初期ソースコード)
全てのノードの変数valueのうち,「0」の個数を表示するために,
関数Number_Checkを作成しなさい.
(関数Number_Check以外は,変更してはいけません)」
という問題の解答例なのですが、Initialize関数の部分でどのように、どのような木構造を作っているのかが理解できません。
疑問点としては、以下の3つで、
・以下のコードの「Node* next[MAX_NUMBER];」の部分は配列のノード版のようなものなのでしょうか?
C++
1class Node { 2public: 3 int value; 4 Node* next[MAX_NUMBER]; 5};
・8行目の「int num[MAX_LEVEL];」の存在意義は何なのでしょうか?
・Initialize関数は一回の再帰呼び出しで何個のノードを作っているのでしょうか?
疑問点が多くて申し訳ないのですが、教えていただければ幸いです
ソースコード全文
C++
1#include<iostream> 2#include<fstream> 3using namespace std; 4 5#define MAX_LEVEL 4 6#define MAX_NUMBER 5 7 8int num[MAX_LEVEL]; 9 10//節点を表すクラス 11class Node { 12public: 13 int value; 14 Node* next[MAX_NUMBER]; 15}; 16 17//木構造作成 18void Initialize(Node* init_node, int level) { 19 init_node->value = rand() % 10; //0~9までの一様乱数を代入 20 for (int i = 0; i < MAX_NUMBER; i++) { 21 if (level != 0) { 22 init_node->next[i] = new Node(); 23 Initialize(init_node->next[i], level - 1); 24 } 25 else { 26 init_node->next[i] = NULL; 27 } 28 } 29} 30 31//0の個数カウント 32int Number_Check(Node* current_node, int current_num) { 33 if (current_node->value == 0) { 34 current_num++; 35 } 36 for (int i = 0; i < MAX_NUMBER; i++) { 37 if (current_node->next[i] != NULL) { 38 current_num = Number_Check(current_node->next[i], current_num); 39 } 40 else { 41 return current_num; 42 } 43 } 44 return current_num; 45 46} 47 48 49void main() { 50 srand(0); //rand関数の初期化 51 Node* root = new Node(); //根ノード 52 53 //木構造の初期化 54 Initialize(root, MAX_LEVEL - 1); 55 //数字の検査 56 cout << Number_Check(root, 0) << endl; 57} 58
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/06/24 05:38