C++ 中二叉樹所有節點的乘積
給定一個包含節點的二叉樹,任務是找到給定二叉樹的所有節點的乘積。
在二叉樹中,有一個根節點,它是樹中所有節點的主節點。一個節點包含資料部分、左指標(將進一步建立左子目錄)和右指標(將有助於建立右子目錄)。因此,要遍歷樹,我們可以使用一個臨時指標,該指標將與左指標關聯以遍歷左子目錄,或與右指標關聯以遍歷右子目錄。
輸入

輸出
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
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP