C++ 中二叉树所有叶节点的乘积
给定一棵包含节点的二叉树,任务是找到给定二叉树的所有叶节点的乘积。
叶节点是没有子节点的末端节点。在树中,节点可以作为父节点或子节点,而根节点只能是父节点。因此,具有 NULL 右指针和左指针的节点是叶节点。
输入
输出
Leaf nodes are -: 23, 34, 25 Product-: 23*34*25 = 19550
解决方案
输入节点数据
从根节点开始遍历所有节点,并转到左子目录或右子目录进行遍历。
将带有 NULL 右指针和左指针的那些节点存储到临时变量中以查找乘积。
打印包含已乘值的临时变量的值。
算法
Start Step 1 → create structure of a node and temp, next and head as pointer to a 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 find product of all the leaf nodes void leaf(node* root, int &product) IF (!root) Return End IF (!root→left && !root→right) Set product *= root→data Call leaf(root→left, product) Call leaf(root→right, product) 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 = 1 Call leaf(root, product) Display product Stop
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
示例
#include <bits/stdc++.h> using namespace std; //structure of a node struct node{ int data; node *left, *right; }; //function to create a new leaf of a tree node* new_node(int data){ node* temp = new node(); temp→data = data; temp→left = temp→right = NULL; return temp; } //function to find the product of all leaf nodes of a tree void leaf(node* root, int &product){ if (!root) return; if (!root→left && !root->right) product *= root→data; leaf(root→left, product); leaf(root→right, product); } int main(){ node* root = new_node(10); root→left = new_node(20); root→left→left = new_node(30); root→left→right = new_node(40); root→right = new_node(50); root→right→right = new_node(60); root→right→left = new_node(70); int product = 1; leaf(root, product); cout<<"product of a leaf nodes are :"<<product; return 0; }
输出
如果运行以上代码,它将生成以下输出 −
product of a leaf nodes are :5040000
广告