0

I want to build a function that receives a tree, and finds the address of a leaf that has a specific value.

typedef struct  treeNode {
    int data;
    struct treeNode* parent;
    struct treeNode* left;
    struct treeNode* right;
} TreeNode;

typedef struct tree {
    TreeNode* root;
    List leafList;   
} Tree;

function:
TreeNode* findParent(Tree tr, int parentData, int branchSelect)
{
    TreeNode* ans = createNewTreeNode(0, NULL, NULL);
    ans = findParentRec(tr.root, parentData, branchSelect);
    return ans;
}


// BUG TO CHECK: WHY MY OUTPUT IS AN EMPTY TREENODE ?!?!?!??!?!?!??!?!?
TreeNode* findParentRec(TreeNode* tr, int parentData, int branchSelect)
{
    if (tr == NULL)
    {
        return;
    }
    else if (tr->data == parentData)
    {
        if ((branchSelect == LEFT && tr->left == NULL) || (branchSelect == RIGHT && tr->right == NULL))
        {
            return tr;
        }
        else
        {
            tr = findParentRec(tr->left, parentData, branchSelect);
            tr = findParentRec(tr->right, parentData, branchSelect);
        }
    }
    else
    {
       tr = findParentRec(tr->left, parentData, branchSelect);
       tr = findParentRec(tr->right, parentData, branchSelect);
    }
}

For example, we have a tree that has a leaf, with data of "20". I'm recursively trying to find it, and when I found (the data HAS to be somewhere in the tree), I want to return it. The problem is, when I find my data and return it, the value that I receive in

ans = findParentRec(tr.root, parentData, branchSelect);

is an empty treenode. For example: enter image description here

My goal is to find "17" in this tree. But when I find it, my output in ans is a treenode with data "0" or 1. BUT my recursive program DO find the specific treenode, and returns it.

Where am I wrong here? How can I change the program that will return me the actual TreeNode* that I need?

Big thanks in advance.

thatDude
  • 45
  • 5
  • 2
    You're not doing anything with the results of the recursive calls. – Barmar Apr 29 '21 at 05:28
  • 2
    `return;` is not valid. The function is declared to return a value, you can't use `return` without an expression. Use `return NULL;` if you have nothing to return. – Barmar Apr 29 '21 at 05:28
  • 1
    Did you ignore the compiler warnings? Don't... – Support Ukraine Apr 29 '21 at 05:30
  • 1
    @4386427 You're right. I forgot that C's `||` always returns a boolean, not one of the operands. – Barmar Apr 29 '21 at 05:41
  • 1
    After you assign the `tr` value, you need to check if it's NULL. If not, return it, otherwise make the next recursive call and return that. – Barmar Apr 29 '21 at 05:42

0 Answers0