求树的父节点(C语言)

一、孩子兄弟表示法C定义

typedef struct Node {
    int data;
    struct Node * leftChild;
    struct Node * rightSibling;
)TreeNode;

二、代码

TreeNode * findParent (TreeNode * root, TreeNode * q){
    // root为根节点, 寻找节点q的双亲

    TreeNode * p = roo;
    if (root == NULL || root->leftChild == NULL)
        return NULL;
    else if (root->leftChild->data == q->data)
        return root;
    else {
        p = root->leftChild->rightSibling;
        while (p) {
               if (p->data == q->data){
                    return root;
                else
                    p = p->rightSibling;
        }
    }
    if ( p = findParent(root->leftChild)
        return p;
    else
        return findParent(root->leftChild->rightSibling);
}

猜你喜欢

转载自blog.csdn.net/weixin_43537097/article/details/128501091