MHB Computing Binary Tree Sums without Globals/Statics

AI Thread 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)
 
Dear Peeps I have posted a few questions about programing on this sectio of the PF forum. I want to ask you veterans how you folks learn program in assembly and about computer architecture for the x86 family. In addition to finish learning C, I am also reading the book From bits to Gates to C and Beyond. In the book, it uses the mini LC3 assembly language. I also have books on assembly programming and computer architecture. The few famous ones i have are Computer Organization and...
I have a quick questions. I am going through a book on C programming on my own. Afterwards, I plan to go through something call data structures and algorithms on my own also in C. I also need to learn C++, Matlab and for personal interest Haskell. For the two topic of data structures and algorithms, I understand there are standard ones across all programming languages. After learning it through C, what would be the biggest issue when trying to implement the same data...
Back
Top