![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Programmer
Join Date: Mar 2005
Location: USA
Posts: 60
Rep Power: 4
![]() |
Counting Number of Leaf Nodes Recursively(Binary Search Tree)
I'm trying to write a function that counts the total number of leaf nodes in a binary search tree:
int tree::sumLeaf(node* node1) {
int sumnodes = 0;
if(node1==NULL){
return (0);
}
sumnodes=sumLeaf(node1->left);
if(node1!=NULL && node1->left==NULL && node1->right==NULL){
return sumnodes++;
} . |
|
|
|
|
|
#2 |
|
Expert Programmer
Join Date: Dec 2004
Posts: 794
Rep Power: 4
![]() |
//UNTESTED!
int tree::sumLeaf(node* node1)
{
if(node1 == NULL) return 0;
return sumLeaf(node1->left) + sumLeaf(node1->right) + 1;
} |
|
|
|
|
|
#3 |
|
Programmer
Join Date: Mar 2005
Location: USA
Posts: 60
Rep Power: 4
![]() |
Thank you for your prompt reply uman, but this function counts the total number of all the nodes, not the number of leaf nodes.
|
|
|
|
|
|
#4 |
|
Expert Programmer
Join Date: Dec 2004
Posts: 794
Rep Power: 4
![]() |
whoops :-P. Sorry. Let me finish cleaning my room and I'll see what I can do.
|
|
|
|
|
|
#5 |
|
Programmer
Join Date: Mar 2005
Location: USA
Posts: 60
Rep Power: 4
![]() |
I don't even know if this is right(now I'm trying to count all the leaf nodes,right and left, not like the first one above):
int tree::sumLeaf(node* node1) {
int sumnodes = 0;
if(node1==NULL){
return (0);
}
sumnodes=sumLeaf(node1->left);
sumnodes=sumLeaf(node1->right);
if(node1!=NULL && node1->left==NULL && node1->right==NULL){
return sumnodes++;
}
else
return sumnodes;
} |
|
|
|
|
|
#6 |
|
Expert Programmer
Join Date: Dec 2004
Posts: 794
Rep Power: 4
![]() |
Try this.
//UNTESTED!
int tree::sumLeaf(node* node1)
{
if(node1 == NULL) return 0;
if(node1->left == NULL && node1->right == NULL) return 1;
else return sumLeaf(node1->left) + sumLeaf(node1->right);
} |
|
|
|
|
|
#7 |
|
Programmer
Join Date: Mar 2005
Location: USA
Posts: 60
Rep Power: 4
![]() |
Damn dude, you rock! It prints 4, and yeah, the leaf nodes are 4 when I tried to draw the tree. Thx!
|
|
|
|
|
|
#8 |
|
Expert Programmer
Join Date: Dec 2004
Posts: 794
Rep Power: 4
![]() |
heh, no problem
![]() |
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|