[英]C++: Sum of all node values of a binary tree
我正在准備面試。 我被困在二叉樹問題之一:
我們如何計算二叉樹所有節點中存在的值的總和?
優雅的遞歸解決方案(偽代碼):
def sum (node):
if node == NULL:
return 0
return node->value + sum (node->left) + sum (node->right)
然后使用:
total = sum (root)
這正確處理NULL根節點的情況。
如果你想在C ++中看到它的運行,這里有一些使用該算法的代碼。 首先,節點的結構和sum
函數:
#include <iostream>
typedef struct sNode {
int value;
struct sNode *left;
struct sNode *right;
} tNode;
int sum (tNode *node) {
if (node == 0) return 0;
return node->value + sum (node->left) + sum (node->right);
}
然后下面的代碼是用於插入節點的測試工具代碼:
static tNode *addNode (tNode *parent, char leftRight, int value) {
tNode *node = new tNode();
node->value = value;
node->left = 0;
node->right = 0;
if (parent != 0) {
if (leftRight == 'L') {
parent->left = node;
} else {
parent->right = node;
}
}
return node;
}
最后,構建以下樹的主要功能,一個涵蓋所有有效可能性的樹(空節點,有兩個子節點的節點,沒有子節點的節點,一個右子節點和一個左子節點):
10
/ \
7 20
/ \
3 99
\
4
\
6
構建該樹並在各個點報告總和的代碼如下所示:
int main (void) {
// Empty tree first.
tNode *root = 0;
std::cout << sum (root) << '\n';
// Then a tree with single node (10).
root = addNode (0, ' ', 10);
std::cout << sum (root) << '\n';
// Then one with two subnodes (10, 7, 20).
addNode (root,'L',7);
addNode (root,'R',20);
std::cout << sum (root) << '\n';
// Then, finally, the full tree as per above.
addNode (root->left,'L',3);
addNode (root->left->left,'R',4);
addNode (root->left->left->right,'R',6);
addNode (root->right,'R',99);
std::cout << sum (root) << '\n';
return 0;
}
這輸出(正確):
0
10
37
149
以任何順序(pre,post,in)遍歷樹。 而不是打印節點計算總數。
void sum(Node* root, int& total)
{
if(root == NULL)
{
return;
}
sum(root->left, total);
total = total + root->value;
sum(root->right, total);
}
int main()
{
int total =0;
sum(root,total);
cout << total;
}
搜索樹,或顯示每個節點或任何其他樹范圍操作的方式相同:訪問當前節點,訪問左子樹(遞歸),並訪問右子樹(遞歸)。
基本上,這樣的事情:
int TreeNode::calculateSum() const
{
int sum = this->value;
if (this->left != NULL) sum += this->left ->calculateSum();
if (this->right != NULL) sum += this->right->calculateSum();
return sum;
}
由於if
檢查遞歸最終會在到達沒有左或右子節點(葉節點)的節點時觸底。
雖然STL具有更復雜和簡潔的機制來實現這一點,但只需學習在容器上使用手動循環就可以非常快速地提高工作效率,例如:
Tree::value_type total = Tree::value_type();
for (Tree::const_iterator i = tree.begin(); i != tree.end(); ++i)
total += *i;
假設您的二叉樹是STL :: map,或者如果不是,您將為自己的實現提供迭代器概念....
使用Tree Traversal技術之一(按順序,預訂,后序)訪問每個節點並將總和存儲在變量中。
您可以在此Wiki中找到有關樹遍歷的更多詳細信息
50 / \\ 30 70 / \\ / \\ 20 40 60 80
收益:350
int Sum(struct node *root)
{
if(root->left == NULL && root->right== NULL)
return root->key;
int lvalue,rvalue;
lvalue=Sum(root->left);
rvalue=Sum(root->right);
return root->key+lvalue+rvalue;
}
public int sum(Node root){
if(root==null){
return 0;
}
if(root.left == null && root.right==null){
return root.key;
}
return sum(root.left)+sum(root.right)+root.key;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.