pax*_*blo 24
优雅的递归解决方案(伪代码):
def sum (node):
if node == NULL:
return 0
return node->value + sum (node->left) + sum (node->right)
Run Code Online (Sandbox Code Playgroud)
然后使用:
total = sum (root)
Run Code Online (Sandbox Code Playgroud)
这正确处理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);
}
Run Code Online (Sandbox Code Playgroud)
然后下面的代码是用于插入节点的测试工具代码:
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;
}
Run Code Online (Sandbox Code Playgroud)
最后,构建以下树的主要功能,一个涵盖所有有效可能性的树(空节点,有两个子节点的节点,没有子节点的节点,一个右子节点和一个左子节点):
10
/ \
7 20
/ \
3 99
\
4
\
6
Run Code Online (Sandbox Code Playgroud)
构建该树并在各个点报告总和的代码如下所示:
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;
}
Run Code Online (Sandbox Code Playgroud)
这输出(正确):
0
10
37
149
Run Code Online (Sandbox Code Playgroud)
以任何顺序(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;
}
Run Code Online (Sandbox Code Playgroud)