Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

จำนวนโหนดลีฟในทรีย่อยของทุกโหนดของทรี n-ary ใน C++


ในบทช่วยสอนนี้ เราจะเขียนโปรแกรมที่ค้นหาจำนวนโหนดปลายสุดสำหรับทุกโหนดในแผนผัง n-ary

จากต้นไม้ n-ary เราต้องหาจำนวน leaf nodes สำหรับทุก subtree มาดูตัวอย่างกัน

ป้อนข้อมูล

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-ary ด้วยต้นไม้ที่คุณชอบ

  • ใช้ 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