根据遍历序列构建二叉树,并转换成双向链表

RT,根据前序和中序遍历结果,构建二叉树,在此基础上把该二叉树转换成双向链表

#include <iostream>
#include <algorithm>

using namespace std;

typedef struct TNode{
        int val;
        struct TNode *lchild;
        struct TNode *rchild;
}TNode, *BTree;

TNode *BuildTree(int pre[], int in[], int len) {
        if (len <= 0)
                return NULL;

        TNode *p = (TNode*)malloc(sizeof(TNode));
        p->val = pre[0];

        int *index = find(in, in+len, pre[0]);

        int dis = index - in;
        p->lchild = BuildTree(pre+1, in, dis);
        p->rchild = BuildTree(pre+dis+1, in+dis+1, len-dis-1);

        return p;
}

void InOrder(BTree T) {//用来测试
        if(T == NULL)
                return;
        InOrder(T->lchild);
        cout<<T->val<<" ";
        InOrder(T->rchild);
}
void PostOrder(BTree T) {//用来测试
        if(T == NULL)
                return;
        PostOrder(T->lchild);
        PostOrder(T->rchild);
        cout<<T->val<<" ";
}

void BuildBiList(BTree T, TNode **lastnode) {
        if (T == NULL)
                return ;
        TNode * current = T;
        BuildBiList(T->lchild, lastnode);

        current->lchild = *lastnode;
        if (*lastnode != NULL)
                (*lastnode)->rchild = current;
        *lastnode = current;
        BuildBiList(T->rchild, lastnode);
}

int main() {
        //int pre[] = {1, 2, 4, 3};//测试用例
        //int in[] = {4, 2, 1, 3};
        int pre[] = {5, 3, 1, 4, 8, 6, 9};
        int in[] = {1, 3, 4, 5, 6, 8, 9};

        BTree T = BuildTree(pre, in, 7);
        InOrder(T);//测试构建结果
        cout<<endl;
        PostOrder(T);
        //转换成双向链表
        TNode * p = NULL;
        BuildBiList(T, &p);//返回的是尾端节点

        //逆向打印
        while (p != NULL) {
                cout << p->val<< " ";
                p = p->lchild;
        }
}
点赞