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

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;
        }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值