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