Void Recursive -> Int Recursive Conversion

Below is the method I've got, however instead of using a return I'm storing the result in a global variable searchdata. This works however would not be elegant coding as return type methods are there for a reason.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void BinarySearchTree::inorder(tree_node* p, int searchTerm)
{
    if(p != NULL)
    {
        if(p->left)
            inorder(p->left);

        if(p->data == searchTerm)
        {
            searchdata = p->data;
        }

        if(p->right)
            inorder(p->right);
    }
    else return;
}


I would like to convert the above to a recursive int method however cannot get it right. I've tried this below, yet it is only returning the value of the outer recursion.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
int BinarySearchTree::inorderX(tree_node* p, int searchTerm)
{
    if(p != NULL)
    {
        cout << "Data (1) : " << p->data << endl;
        cout << "Test Val : " << test << endl;
        cout << "Compare" << (test == p->data) << endl;

        if(test == p->data)
        {
            cout << "TRUE HERE";
            return (p->data);
        }
        else
        {

            if(p->left != NULL)
            {
                return inorderX(p->left,test);
            }

            if(p->right != NULL)
            {
                return inorderX(p->right,test);
      
            }
        }

        return -1;

    }
}


Sorry I would like to add that these methods are not for inorder traversing, but actually for searching, forgot to rename them!!

The binary tree is not a binary search tree.. eg. the left node may not be smaller than the parent node, and vice versa etc.
Topic archived. No new replies allowed.