把二叉树转化成双向连表

#include <stdio.h>
#include <stdlib.h>
 
struct BSTreeNode {
    int m_Value;
    struct BSTreeNode *m_pLeft;
    struct BSTreeNode *m_pRight;
};
 
void MidOrderVisit(struct BSTreeNode *root)
{
    if (root == NULL)
        return;
     MidOrderVisit(root->m_pLeft);
 
     printf("%d\n", root->m_Value);
      
     MidOrderVisit(root->m_pRight);
}
 
void CreateList(struct BSTreeNode *root, struct BSTreeNode **list)
{
    if (root == NULL)
        return;
    CreateList(root->m_pLeft, list);
    root->m_pLeft = *list;
    *list = root;
    CreateList(root->m_pRight, list);
}
 
struct BSTreeNode *CreateDoubleList(struct BSTreeNode *root)
{
    struct BSTreeNode *list = NULL;
    CreateList(root, &list);
    root = list;
    root->m_pRight = NULL;
    while (root->m_pLeft != NULL) {
        root->m_pLeft->m_pRight = root;
        root = root->m_pLeft;
    }
    return list;
}
        
        
int InsertNode(struct BSTreeNode **root, int value)
{
    struct BSTreeNode *node = *root;
    struct BSTreeNode *p;
    p = calloc(1, sizeof(struct BSTreeNode));
    p->m_Value = value;
 
    while (node != NULL) {
        if (node->m_Value == value)
            return value;
        else if (node->m_Value > value) {
            if (node->m_pRight != NULL)
                node = node->m_pRight;
            else {
                node->m_pRight = p;
                return 0;
            }
        }
        else {
            if (node->m_pLeft != NULL)
                node = node->m_pLeft;
            else {
                node->m_pLeft = p;
                return 0;
            }
        }
    }
 
    *root = p;
    return 0;
}
 
void ShowList(struct BSTreeNode *root)
{
    struct BSTreeNode *node = root;
    printf("prev:");
    while (node != NULL) {
        printf("%d ", node->m_Value);
        if (node->m_pLeft != NULL)
            node = node->m_pLeft;
        else
            break;
    }
    printf("\nnext:");
    while (node != NULL) {
        printf("%d ", node->m_Value);
        node = node->m_pRight;  
    }
    printf("\n");
}
 
 
int main()
{
    int i = 0;
    int array[9] = {16, 7, 12, 13, 15, 24, 6, 25, 27};
    struct BSTreeNode *root = NULL;
    struct BSTreeNode *list = NULL;
    while (i < 9) {
        InsertNode(&root, array[i]);
        i++;
    }
    MidOrderVisit(root);
    fflush(NULL);
    list = CreateDoubleList(root);
    ShowList(list);
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值