二元查找树转换为排序的双向链表

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

            10

        /         \

    6              14

/       \        /      \

4       8    12       16

转换为双向链表

4=6=8=10=12=14=16。

二叉查找树节点的数据结构如下:

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

这里首先给出构建二叉搜索树的简单实现:

/**
*	ipNode: node of the tree
*	iValue: value of node
*/
BSTreeNode* InsertBSTreeNode(BSTreeNode* ipNode, int iValue)
{
	if (nullptr == ipNode)
	{
		ipNode = new BSTreeNode;
		ipNode->m_nValue = iValue;
		ipNode->m_pLeft = nullptr;
		ipNode->m_pRight = nullptr;
	}
	else
	{
		if (ipNode->m_nValue > iValue)
			ipNode->m_pLeft = InsertBSTreeNode(ipNode->m_pLeft, iValue);
		if (ipNode->m_nValue < iValue)
			ipNode->m_pRight = InsertBSTreeNode(ipNode->m_pRight, iValue);
	}

	return ipNode;
}

然后通过递归方法实现二叉搜索树的转换:

/**
*    ioHeadPtr:    pointer point to first node of converted double linked list
*    ioTailPtr:    pointer point to last node of converted double linked list
*    ipRoot:       root node of BSTree
*/
void ConvertBSTree2ListHelper(BSTreeNode*& ioHeadPtr, BSTreeNode*& ioTailPtr, BSTreeNode* ipRoot)
{
    if (ipRoot == nullptr)
    {
        ioHeadPtr = nullptr;
        ioTailPtr = nullptr;
        
        return;
    }

    BSTreeNode *lpLeftTail, *lpRightHead;

    ConvertBSTree2ListHelper(ioHeadPtr, lpLeftTail, ipRoot->m_pLeft);
    ConvertBSTree2ListHelper(lpRightHead, ioTailPtr, ipRoot->m_pRight);

    if (lpLeftTail != nullptr)
    {
        lpLeftTail->m_pRight = ipRoot;
        ipRoot->m_pLeft = lpLeftTail;
    }
    else
    {
        ioHeadPtr = ipRoot;
    }

    if (lpRightHead != nullptr)
    {
        lpRightHead->m_pLeft = ipRoot;
        ipRoot->m_pRight = lpRightHead;
    }
    else
    {
        ioTailPtr = ipRoot;
    }
}

BSTreeNode* ConvertBSTree2List(BSTreeNode* ipRoot)
{
    BSTreeNode *lHeadPtr, *lTailPtr;

    ConvertBSTree2ListHelper(lHeadPtr, lTailPtr, ipRoot);
    
    return lHeadPtr;
}

 

转载于:https://my.oschina.net/u/3349205/blog/1341365

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值