简体   繁体   English

如何在非变体二叉树中搜索给定节点的父节点?

[英]How to search parent Node of a given Node in a non variant Binary Tree?

I have the code for searching a node in a Binary Tree.我有在二叉树中搜索节点的代码。 How can I find the parent of the Node whose KEY is provided as an argument?如何找到将KEY作为参数提供的节点的父节点?

Here is the code for Normal search for a Binary Tree -这是二叉树的正常搜索代码 -

struct Tree* search(struct Tree *root, int KEY)
{
    struct Tree *temp;
    if(root == NULL) return NULL; //Base condition
    else
    {
        if(root-> data == KEY) return root;
        else
        {
            temp = search(root-> Lchild, KEY);
            if(temp != NULL) return temp;
            else return(search(root-> Rchild, KEY));
        }
    }
    return NULL;
}

You are returning the address of the Tree node whose value matches with the KEY , not it's parent.您正在返回值与KEY匹配的Tree节点的地址,而不是它的父节点。 Assuming that all the node values are distinct in this tree, you have to follow the below code to return the parent Tree node address if it's child node (left or right child) value matches with the KEY .假设这棵树中的所有节点值都是不同的,如果它的子节点(左子节点或右子节点)值与KEY匹配,则必须按照以下代码返回父Tree节点地址。

struct Tree* search(struct Tree *root, int KEY){
    if(root == NULL){
        return NULL;
    }
    if(root->Lchild != NULL && root->Lchild->data == KEY){
        return root;
    }
    if(root->Rchild != NULL && root->Rchild->data == KEY){
        return root;
    }
    struct Tree *left = search(root->Lchild, KEY);
    struct Tree *right = search(root->Rchild, KEY);
    if(left != NULL){
        return left;
    }else if(right != NULL){
        return right;
    }
    return NULL;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM