获取一颗二叉树的中序后继节点

定义二叉树

二叉树除了有左右孩子节点外还有父母节点parent

代码

//获取中序后继节点
class CNode{
public:
    int value;
    CNode *left;
    CNode *right;
    CNode *parent;
    CNode(int value):
    value(value){
        left = nullptr;
        right = nullptr;
        parent = nullptr;
    }
};

CNode* CBTInit(){
    CNode* head = new CNode(4);
    head->left = new CNode(2);
    head->left->parent = head;
    head->right = new CNode(6);
    head->right->parent = head;
    head->left->left = new CNode(1);
    head->left->left->parent = head->left;
    head->left->right = new CNode(3);
    head->left->right->parent = head->left;
    head->right->left = new CNode(5);
    head->right->left->parent = head->right;
    head->right->right = new CNode(7);
    head->right->right->parent =  head->right;
    return head;
}

CNode* getLastLeft(CNode* o){
    if(o == nullptr){
        return nullptr;
    }
    while(o->left != nullptr){
        o = o->left;
    }
    return o;
}
CNode* getSuccessor(CNode *o){
    if(o == nullptr){
        return nullptr;
    }
    if(o->right != nullptr){
        return getLastLeft(o->right);
    }else{
        while(o->parent != nullptr
        &&
        o == o->parent->right){
            o = o->parent;
        }
        return o->parent;
    }
}

posted @ 2021-08-03 18:17  蘑菇王国大聪明  阅读(43)  评论(0编辑  收藏  举报