中序線索二叉樹的構造和遍歷

blabla發表於2019-11-13

中序線索二叉樹的構造

結構體

typedef struct ThreadNode{
    int data;
    int lTag, rTag;
    struct ThreadNode *lChild, *rChild;
}ThreadNode, *ThreadTree;

遞迴演算法

void inThread(ThreadTree &p, ThreadTree &pre){
    while(p){
        inThread(p->lChild, pre); //線索化左子樹
        if(p->lChild == NULL){
            p->lChild = pre;
            pre->lTag = 1;
        }
        if(pre != NULL && pre->rChlld == NULL){
            pre->rChild = p;
            pre->rTag = 1;
        }
        pre = p;
        inThread(p->rChild, pre);
    }
}

通過中序遍歷線索化二叉樹主過程

void createThreadTree(ThreadTree root){
    ThreadTree pre = NULL;
    if(p){
        inThread(root, pre);
        pre -> rChild = NULL;
        pre -> rTag = 1;
    }
}

中序線索二叉樹的遍歷

求線索二叉樹的第一個結點

ThreadNode* FirstNode(ThreadTree root){
    while(root->lTag == 0) root = root->lChild;
    return root;
}   

給定結點,求線索二叉樹的後一個結點

ThreadNode* nextNode(ThreadNode p){
    if(p->rTag == 1) return p->rChild;
    return FirstNode(p->rChild);
}

求線索二叉樹的最後一個結點

ThreadNode* lastNode(ThreadTree root){
    if(root->rChild == NULL) return root;
    ThreadNode *pre, *p;
    while(p != NULL){
        pre = p;
        p = NextNode(p);
    }
    return pre;
}

給定結點p,求結點的前驅

ThreadNode* preNode(ThreadNode *p){
    if(p->lTag == 1) return p->lChild;
    ThreadNode *pre, *q= NextNode(p->lChild);
    while(q != p){
        pre = q;
        q = NextNode(q);
    }
    return pre;
}   

遍歷中序二叉樹

void inOrder(ThreadTree root){
    while(ThreadNode *p = FirstNode(root); p != NULL; p = NextNode(p)) cout << p->data << " ";
    cout << endl;
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章