ให้ด้วยไบนารีทรีที่มีโหนด และภารกิจคือการค้นหาผลคูณของโหนดทั้งหมดของไบนารีทรีที่กำหนด
ในไบนารีทรี จะมีโหนดรูทซึ่งเป็นโหนดหลักของโหนดทั้งหมดในทรี โหนดประกอบด้วยส่วนข้อมูล ตัวชี้ด้านซ้าย ซึ่งจะสร้างไดเรกทอรีย่อยด้านซ้ายและตัวชี้ด้านขวา ซึ่งจะช่วยในการสร้างไดเรกทอรีย่อยที่ถูกต้อง เพื่อสำรวจต้นไม้ เราสามารถใช้ตัวชี้ชั่วคราวที่จะเชื่อมโยงกับตัวชี้ด้านซ้ายเพื่อสำรวจไดเรกทอรีย่อยด้านซ้ายหรือตัวชี้ขวาเพื่อสำรวจไดเรกทอรีย่อยด้านขวา
ป้อนข้อมูล

ผลผลิต
Nodes are-: 10, 20, 30, 40, 50, 60 Product = 10*20*30*40*50*60 = 72,00,00,000
แนวทาง
-
ป้อนข้อมูลโหนด
-
ข้ามโหนดทั้งหมดที่เริ่มต้นจากโหนดรูทและไปที่ไดเร็กทอรีย่อยด้านซ้ายหรือไดเร็กทอรีย่อยด้านขวาสำหรับการข้ามผ่าน
-
เก็บข้อมูลโหนดและคูณข้อมูลที่เก็บไว้ด้วยข้อมูลใหม่
-
พิมพ์ค่าของตัวแปรชั่วคราวที่เก็บค่าที่คูณไว้
อัลกอริทึม
Start Step 1 → create structure of a node structure node struct node int data Create node *left, *right End Step 2 → declare function to insert a node in a tree node* new_node(int data) Set node* temp = new node() Set temp→data = data Set temp→left = temp→right = NULL return temp End Step 3 → Declare a function to multiply all the nodes void leaf(node* root, int &product) IF root = NULL return 1 End return (root→data * node_product(root→left) * node_product(root→right)) Step 4 → In main() Create node* root = new_node(10) Set root→left = new_node(20) Set root→left→left = new_node(30) Set int product = node_product(root) Display product Stop
ตัวอย่าง
#include <iostream>
using namespace std;
//structure of a node
struct node{
int data;
node *left, *right;
};
//function for inserting a new node
node* new_node(int data){
node* temp = new node();
temp→data = data;
temp→left = temp→right = NULL;
return temp;
}
//function for multiplying all the nodes
int node_product(node* root){
if (root == NULL)
return 1;
return (root→data * node_product(root→left) * node_product(root→right));
}
int main(){
node* root = new_node(10);
root→left = new_node(20);
root→right = new_node(30);
root→left→left = new_node(40);
root→left→right = new_node(50);
root→right→left = new_node(60);
int product = node_product(root);
cout << "Product of all the nodes is: "<<product<< endl;
return 0;
} ผลลัพธ์
หากรันโค้ดด้านบน มันจะสร้างผลลัพธ์ต่อไปนี้ -
Product of all the nodes is: 720000000