二叉搜索树与双向链表

输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建新的节点,只能调整树中节点指针的指向。

由于要求转换后的链表是排好序的,我们可以用中序遍历树的每一个节点。

下面是代码:

struct BinaryTreeNode
{
    int value;
    BinaryTreeNode* p_left;
    BinaryTreeNode* p_right;
};

void ConvertNode(BinaryTreeNode* pNode, BinaryTreeNode** pLastNodeInList)
{
    if( pNode == NULL)
        return;

    BinaryTreeNode* pCurrent = pNode;
    if( pCurrent->p_left !=NULL)
        ConvertNode(pCurrent->p_left,pLastNodeInList);

    //改变节点的左右指针指向
    pCurrent->p_left = *pLastNodeInList;
    if( (*pLastNodeInList) != NULL )
        (*pLastNodeInList)->p_right = pCurrent;
    
    //移动指向节点的指针
    *pLastNodeInList = pCurrent;

    if( pCurrent->p_right != NULL)
        ConvertNode(pCurrent->p_right,pLastNodeInList);
}


BinaryTreeNode* Convert(BinaryTreeNode* pRoot)
{
    BinaryTreeNode* pLastNodeInList = NULL;

    ConvertNode(pRoot,&pLastNodeInList);

    //pLastNodeInlist指向双向链表的尾部,我们需要返回头节点
    BinaryTreeNode* pHeadOfList = pLastNodeInList;
    while( pHeadOfList !=NULL && pHeadOfList->p_left !=NULL)
        pHeadOfList = pHeadOfList->p_left;

    return pHeadOfList;
}

 

posted @ 2013-03-07 13:09  没离开过  阅读(109)  评论(0编辑  收藏  举报