用 C++ 找出給定的完全二叉樹中所有節點的和


假設我們有一個正整數 L,它表示完美二叉樹中的層數。該完美二叉樹中的葉節點從 1 到 n 編號。其中 n 是葉節點數。父節點是子節點的和。我們的任務是編寫一個程式來列印此完美二叉樹的所有節點的和。因此,如果樹像下面這樣 −

則總和為 30。

如果仔細觀察,我們需要找出所有節點的和。由於葉節點的值從 1 到 n,那麼我們可以使用公式 n(n+1)/2 獲得葉節點的和。由於這是一個完美的二叉樹,所以每層的和都是相同的。因此,找到最後一層的和,然後將其乘以層數。

示例

 現場演示

#include<iostream>
#include<cmath>
using namespace std;
int treeSum(int level) {
   int total_leaves = pow(2, level - 1);
   int leaf_sum = 0;
   leaf_sum = (total_leaves * (total_leaves + 1)) / 2;
   int sum = leaf_sum * level;
   return sum;
}
int main() {
   int levels = 4;
   cout << "Sum of all nodes for a perfect binary tree with level " << levels << " is: " << treeSum(levels);
}

輸出

Sum of all nodes for a perfect binary tree with level 4 is: 144

更新日期:2019 年 12 月 17 日

146 條瀏覽

開始您的職業

完成本課程獲得認證

開始
廣告
© . All rights reserved.