Computing Binary Tree Sums without Globals/Statics

Click For Summary
SUMMARY

The discussion focuses on creating an algorithm to compute the sum of the keys in a binary tree without using global or static variables. The proposed recursive function, S(NODE *P), correctly sums the node values by recursively calling itself for the left and right children. The final implementation ensures that local variables are utilized effectively, maintaining the integrity of the recursive process. The algorithm is confirmed to be correct by participants in the discussion.

PREREQUISITES
  • Understanding of binary tree data structures
  • Proficiency in C/C++ programming language
  • Knowledge of recursion and its application in algorithms
  • Familiarity with function pointers and node structures in C/C++
NEXT STEPS
  • Study recursive algorithms for tree traversal techniques
  • Learn about memory management in C/C++ to avoid globals and statics
  • Explore advanced data structures, such as AVL trees or Red-Black trees
  • Investigate optimization techniques for recursive functions in C/C++
USEFUL FOR

Software developers, algorithm enthusiasts, and computer science students interested in mastering binary tree operations and recursive programming techniques.

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)
 

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
2K
  • · 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