Home > Software design >  C binary tree search and count how many times a condition is happening
C binary tree search and count how many times a condition is happening

Time:01-05

I need to go through a binary tree and count how many times a condition is happening. I have tried to return both leaves and 1 in the same time if the condition happened else return them with 0. Any chance for ideas?

int countChoose(BinTree *root) {
    if (root == NULL)
        return 0;
    updateTask(root);
    if (root->whatToDo == COUNT_MALE_ORDER) {
        if (root->gender == 'M') {
            return 1   countChoose(root->left)  
                       countChoose(root->right);

        }
        return 0   countChoose(root->left)  
                   countChoose(root->right);
    }

}

CodePudding user response:

Without knowing exactly what the problem is, it looks like the last return statement should be moved outside of the outer if statement, i.e.,:

int countChoose(BinTree *root) {
    if (root == NULL)
        return 0;
    updateTask(root);
    if (root->whatToDo == COUNT_MALE_ORDER) {
        if (root->gender == 'M') {
            return 1   countChoose(root->left)  
                    countChoose(root->right);
        }
    }
    
    return 0   countChoose(root->left)   countChoose(root->right);
}

CodePudding user response:

Ty for your time and effort. I fix it the problem wasn’t in my function its was in a generic functuin that calls this one. Ty!!! But that’s means a lot for me that you point me to the correct way of work!!

  • Related