C
C
ColdHandGuy2022-01-09 20:32:45
C++ / C#
ColdHandGuy, 2022-01-09 20:32:45

How to find the parent of a given element in a binary tree?

Greetings! Now I am getting acquainted with binary trees and it is necessary to find the parent of the entered element. Wrote the following recursive function, but it does not want to work. Tell me what am I doing wrong?

struct node* searchParent(struct node* root, int x)
{
    if(root->left_child->data == x || root->right_child->data == x)
    {
        return root;
    }
    else
    {
        return searchParent(root->left_child, x);
        return searchParent(root->left_child, x);
    }
}


The structure itself:
struct node
{
    int data; //node will store an integer
    struct node *right_child; // right child
    struct node *left_child; // left child
};

Answer the question

In order to leave comments, you need to log in

2 answer(s)
C
ColdHandGuy, 2022-01-10
@coldhand

I'll leave the solution for the potential following seekers:

struct node* searchParent(struct node* root, int x)
{
    if((root->left_child != NULL && root->left_child->data == x) || (root->right_child != NULL && root->right_child->data == x))
    {
        return root;
    }
    else
    {
        if(root->left_child != NULL && x < root->data)
        {
            return searchParent(root->left_child, x);
        }
        else
            if(root->right_child != NULL && x > root->data)
            {
                return searchParent(root->right_child, x);
            }
    
    }
}

R
res2001, 2022-01-09
@res2001

Because in the else block both calls come with left_child.
And also after the first call there will be a return immediately, because. the calls are in the return statement.
And you need to first check that the child pointers are not nullptr.
In fact, you need one more condition in the else block:

If(root->data < x) return searchParent(root->left_child, x);
Else return searchParent(root->right_child, x);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question