把二元查找树转变成排序的双向链表

题目:输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。

要求:不能创建任何新的结点,只调整指针的指向。

举例:

         10
        /   \        转变
       6     14      -->   4=6=8=10=12=14=16
      / \   /  \
     4   8 12   16

定义的二元查找树结点的数据结构如下:

struct BSTreeNode 
{
    int m_nValue;
    BSTreeNode *m_pLeft;
    BSTreeNode *m_pRight;
};

答:用二叉树的中序遍历

#include "stdafx.h"
#include <iostream>
#include <fstream>

using namespace std;

struct BSTreeNode 
{
    int m_nValue;
    BSTreeNode *m_pLeft;
    BSTreeNode *m_pRight;
};

//创建二元二叉树
void CreateBitree(BSTreeNode *&pNode, fstream &fin)
{
    int dat;
    fin>>dat;
    if(dat==0)
    {
        pNode = NULL;
    }
    else 
    {
        pNode = new BSTreeNode();
        pNode->m_nValue=dat;      
        CreateBitree(pNode->m_pLeft, fin);      
        CreateBitree(pNode->m_pRight, fin);
    }
}

//中序递归转变
void change(BSTreeNode *pNode, BSTreeNode *&pTail)
{
    if (NULL != pNode)
    {
        change(pNode->m_pLeft, pTail);
        if (NULL != pTail)
        {
            pTail->m_pRight = pNode;
        }
        pNode->m_pLeft = pTail;
        pTail = pNode;
        change(pNode->m_pRight, pTail);
    }
}

int _tmain(int argc, _TCHAR* argv[])
{
    BSTreeNode *pRoot = NULL;
    BSTreeNode *pTail = NULL;
    fstream fin("tree.txt");
    CreateBitree(pRoot, fin);
    change(pRoot, pTail);
    while(NULL != pTail)
    {
        cout<<pTail->m_nValue<<"  ";
        pTail = pTail->m_pLeft;
    }

    cout<<endl;
    return 0;
}

运行的界面如下:

建造二叉树用到的tree.txt为:

10 6 4 0 0 8 0 0 14 12 0 0 16 0 0 
posted @ 2012-08-20 20:38  venow  阅读(315)  评论(0编辑  收藏  举报