根據遍歷序列構建二叉樹,並轉換成雙向鏈表

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;
        }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章