二叉树中序线索化和遍历C++

#include 
#include 

using namespace std;

typedef char ElemType;
typedef struct BTnode {
    ElemType data;
    struct BTnode *lchild, *rchild;
    int ltag:4;
    int rtag:4;
} BTnode, *BTree;

BTree pre = NULL;

void inThread(BTree &T) {

    if (T) {
        inThread(T->lchild);

        if (!T->lchild) {
            T->ltag = 1;
            T->lchild = pre;
        } else T->ltag = 0;

        if (pre) {
            if (!pre->rchild) {
                pre->rtag = 1;
                pre->rchild = T;
            } else pre->rtag = 0;
        }

        pre = T;
        inThread(T->rchild);
    }
}

void createInThread(BTree &T) {
    if (T) {
        inThread(T);
        pre->rtag = 1;
        pre->rchild = NULL;
    }

}

void createTree(BTree &T) {
    char ch;
    cin >> ch;
    if (ch == '#') {
        T = NULL;
    } else {
        T = new BTnode;
        T->data = ch;
        createTree(T->lchild);
        createTree(T->rchild);
    }
}

void inOrderTraverse(BTree T) {
    BTree p;
    p = T;

    while (p) {
        while(p->ltag == 0) p = p->lchild;
        cout << p->data << " ";
        while (p->rtag == 1 && p->rchild) {
            p = p->rchild;
            cout << p->data << " ";
        }
        p = p->rchild;
    }
}

//ABD##E##CF#G###
int main() {
    BTree T;
    createTree(T);
    createInThread(T);
    inOrderTraverse(T);
}

你可能感兴趣的:(二叉树中序线索化和遍历C++)