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)
 
Thread 'Star maps using Blender'
Blender just recently dropped a new version, 4.5(with 5.0 on the horizon), and within it was a new feature for which I immediately thought of a use for. The new feature was a .csv importer for Geometry nodes. Geometry nodes are a method of modelling that uses a node tree to create 3D models which offers more flexibility than straight modeling does. The .csv importer node allows you to bring in a .csv file and use the data in it to control aspects of your model. So for example, if you...
I tried a web search "the loss of programming ", and found an article saying that all aspects of writing, developing, and testing software programs will one day all be handled through artificial intelligence. One must wonder then, who is responsible. WHO is responsible for any problems, bugs, deficiencies, or whatever malfunctions which the programs make their users endure? Things may work wrong however the "wrong" happens. AI needs to fix the problems for the users. Any way to...
Back
Top