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
示例
#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
廣告