01二叉查找树转化成双向链表

题目:输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。  要求不能创建任何新的结点,只调整指针的指向。

思路:head指向双向链表头,x指向双向链表尾,中序遍历二叉树,每当遍历一个到一个节点时,将它链接到双向链表尾。

#include <iostream>
using namespace std;
#define MAX 10

struct BSTreeNode
{
    int m_nValue; // value of node
    BSTreeNode *m_pLeft; // left child of node
    BSTreeNode *m_pRight; // right child of node
}*head, *x;

BSTreeNode* InsertTree(BSTreeNode* root, BSTreeNode* z)
{
    BSTreeNode* x = root;
    BSTreeNode* y = NULL;
    while (x) {
        y = x;
        if (x->m_nValue > z->m_nValue) {
            x = x->m_pLeft;
        }
        else if (x->m_nValue < z->m_nValue){
            x = x->m_pRight;
        }
        else {
            cout << "duplicate value during inserting "<< z->m_nValue <<"!\n";
            return root;
        }
    }
    if (!y) {
        root = z;
    }
    else {
        if (y->m_nValue > z->m_nValue) {
            y->m_pLeft = z;
        }
        else {
            y->m_pRight = z;
        }
    }
    return root;
}

void DeleteDoubleList(BSTreeNode* head)
{
    BSTreeNode* p = head;
    while (head) {
        p = head->m_pRight;
        delete head;
        head = p;
    }
}

void PrintDoubleList(BSTreeNode* head)
{
    BSTreeNode* p;
    while (head) {
        p = head->m_pRight;
        cout<<head->m_nValue<<" ";
        head = p;
    }
    cout << endl;
}

void ConvertCurrentNode(BSTreeNode* root)
{
    cout << root->m_nValue << " ";
    if (!head) {
        head = root;
        x = root;
    }
    else {
        x->m_pRight = root;
        root->m_pLeft = x;
        x = root;
    }
}

void ConvertToDoubleList(BSTreeNode* root)
{
    if (!root) return;

    if (root->m_pLeft) {
        ConvertToDoubleList(root->m_pLeft);
    }

    ConvertCurrentNode(root);

    if (root->m_pRight) {
        ConvertToDoubleList(root->m_pRight);
    }
}

int main()
{
    head = NULL;
    x = NULL;

    BSTreeNode* root = NULL;

    int a[MAX] = {10,6,14,4,8,12,16, 17, 5, 11};

    for (int i = 0; i < MAX; ++i) {
        BSTreeNode* z = new BSTreeNode();
        z->m_nValue = a[i];
        z->m_pLeft = NULL;
        z->m_pRight = NULL;
        root = InsertTree(root, z);
    }

    ConvertToDoubleList(root);
    cout << endl;
    cout << "After convert to double list:\n";
    PrintDoubleList(head);

    DeleteDoubleList(head);
    head = NULL;
    cout << "After delete double list:\n";
    PrintDoubleList(head);

    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值