MHB Computing Binary Tree Sums without Globals/Statics

Click For Summary
The discussion centers on creating an algorithm to calculate the sum of the keys in a binary tree without using global or static variables. The proposed code snippets utilize a recursive approach, where the function checks if the node is NULL and returns 0 if so. It then calculates the sum by adding the current node's data to the sums of the left and right subtrees. The initial code had a minor error regarding variable naming, but it was clarified and confirmed as correct. The overall consensus is that the algorithm is valid and effectively accomplishes the task.
evinda
Gold Member
MHB
Messages
3,741
Reaction score
0
Hi! (Wave)

I want to write an algorithm, that counts the sum of the keys of the nodes of a binary tree, without the use of globals and statics.

That's what I have tried:

Code:
S(NODE *P){
 if (P==NULL) return 0;
 int m=P->data+S(P->left);
 int n=m+S(P->right);
 return n;

Could you tell me if it is right? (Thinking)
 
Last edited:
Technology news on Phys.org
evinda said:
Hi! (Wave)

I want to write an algorithm, that counts the sum of the keys of the nodes of a binary tree, without the use of globals and statics.

That's what I have tried:

Code:
S(NODE *P){
 if (P==NULL) return 0;
 int s1=P->data+S(P->left);
 int s2=s1+S(P->right);
 return s2;

Could you tell me if it is right? (Thinking)

It is right. (Smile)
 
evinda said:
Code:
S(NODE *P){
 if (P==NULL) return 0;
 int m=P->data+S(P->left);
 int n=s1+S(P->right);
 return n;
What is [m]s1[/m]?
 
Evgeny.Makarov said:
What is [m]s1[/m]?

With [m] s1 [/m] I meant [m]m[/m], I am sorry... (Smile)
 
I like Serena said:
It is right. (Smile)

Great! Thanks a lot! (Party)
 
Learn If you want to write code for Python Machine learning, AI Statistics/data analysis Scientific research Web application servers Some microcontrollers JavaScript/Node JS/TypeScript Web sites Web application servers C# Games (Unity) Consumer applications (Windows) Business applications C++ Games (Unreal Engine) Operating systems, device drivers Microcontrollers/embedded systems Consumer applications (Linux) Some more tips: Do not learn C++ (or any other dialect of C) as a...

Similar threads

  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 2 ·
Replies
2
Views
1K
  • · Replies 3 ·
Replies
3
Views
4K
  • · Replies 3 ·
Replies
3
Views
2K
Replies
1
Views
1K
  • · Replies 10 ·
Replies
10
Views
3K
Replies
14
Views
3K
  • · Replies 7 ·
Replies
7
Views
2K
Replies
2
Views
2K
  • · Replies 11 ·
Replies
11
Views
3K