I have created a binary tree. I have a function which counts the odd values from nodes of tree.
I am always getting the output as if it is just returning the odd count from node->right.

I am loosing the value of node->left count.

#include <stdio.h>  
#include <stdlib.h>  
#include <iostream>

using namespace std;
   
struct node  
{  
    int data;  
    struct node* left;  
    struct node* right;  
};  

int getLeafCount(struct node* node, int count)  
{	

	int temp = 0;
	if(node!=NULL)  
	{
        if((node -> data %2) != 0)
		{
			temp++;
			count = count + temp;	
		}
		getLeafCount(node->left, count);
		getLeafCount(node->right, count);
				
	}
		return count;
}  

struct node* newNode(int data)  
{  
  struct node* node = (struct node*)malloc(sizeof(struct node));  
  node->data = data;  
  node->left = NULL;  
  node->right = NULL;  
  return(node);  
}  

int main()  
{  
  struct node *root = newNode(1);  
  root->left        = newNode(2);  
  root->right       = newNode(3);  
  root->left->left  = newNode(4);  
  root->left->right = newNode(5);   

  int tot_cnt = getLeafCount(root, 0);
  cout << "Total Count: " << tot_cnt;	

  getchar();  
  return 0;  

}

I am always getting output as 1 instead of 3.
Please help me out.

Thanks

>> if((node -> data %2) != 0)
bad coding. Make a bool isOdd(int n){ return n % 2 == 1; } function
and use it like so if( isOdd(node->data) ){ ...}

Edit: Clarification.
'When' you call getLeafCount(node->right), is the stack value of 'node' the same as when the function began at first?
Short answer: No

int getLeafCount(struct node* node, int count) { 
  int temp = 0;
  if(node!=NULL) {
    if((node -> data %2) != 0) {
      temp++;
      count = count + temp;
    }
    getLeafCount(node->left, count);
    getLeafCount(node->right, count); // 'when' is this called?
  }
return count;
}

The important point here is that a function is just a memory address which reads values from the stack. Even after the function continues execution (after calling getleafcount from inside itself and returning), you've moved left a node, so reading node->right won't be the node you necessarily expect (the stack has changed).

I don't think what you wrote is necessarily the functionality you want.

My problem is solved.
Thanks for the replies.

int getLeafCount(struct node* node, int count)  
{	
	int temp = 0;	

	if(node!=NULL)  	
	{        
		count = getLeafCount(node->left, temp) + getLeafCount(node->right, temp);
		if((node -> data %2) != 0)		
			count ++;
	}		
	return count;
}

Now i want to perform this using iterative method.
Any ideas or algorithms would be really appreciated.

Thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.