【100题】二叉排序树转成双向链表----中序遍历法

#include <stdio.h>
#include <iostream>
using namespace std;
struct BSTreeNode
{
    int m_nValue; // value of node
    BSTreeNode *m_pLeft; // left child of node
    BSTreeNode *m_pRight; // right child of node
};
typedef BSTreeNode DoubleList;
DoubleList * pHead;
// 创建二元查找树
void createBinarySearchTree(BSTreeNode * & pCurrent, int value)
{
    if (NULL == pCurrent)
    {
        BSTreeNode * pBSTree = new BSTreeNode();
        pBSTree->m_pLeft = NULL;
        pBSTree->m_pRight = NULL;
        pBSTree->m_nValue = value;
        pCurrent = pBSTree;
    }
    else 
    {
        if ((pCurrent->m_nValue) > value)
        {//如果比当前节点值小,则放到左子树
            createBinarySearchTree(pCurrent->m_pLeft, value);
        }
        else if ((pCurrent->m_nValue) < value)
        {//如果比当前节点值大,则放到右子树
            createBinarySearchTree(pCurrent->m_pRight, value);
        }
        else
        {//否则提示重复插入了。
            cout<<"重复加入节点"<<endl;
        }
    }
}
//采用中序遍历的方法
void ConvertNode(BSTreeNode *pNode,BSTreeNode *&pLastNodeInList)
{
	if(pNode == NULL)
	{
		return ;
	}
	BSTreeNode *pCurrent = pNode;
	//先递归遍历左子树
	if(pCurrent->m_pLeft != NULL)
	{
		ConvertNode(pCurrent->m_pLeft,pLastNodeInList);
	}
	//把左子树遍历结果连接到当前节点的左边
	pCurrent->m_pLeft = pLastNodeInList;
	if(pLastNodeInList != NULL)
	{
		pLastNodeInList->m_pRight = pCurrent;
	}
	pLastNodeInList = pCurrent;
	if(pCurrent->m_pRight != NULL)
	{
		ConvertNode(pCurrent->m_pRight,pLastNodeInList);
	}
}
//
BSTreeNode *Convert(BSTreeNode *pHeadOfTree)
{
	BSTreeNode *pLastNodeInList = NULL;
	ConvertNode(pHeadOfTree,pLastNodeInList);
	//取得
	BSTreeNode *pHeadOfList = pLastNodeInList;
	while(pHeadOfList && pHeadOfList->m_pLeft)
	{
		pHeadOfList = pHeadOfList->m_pLeft; 
	}
	return pHeadOfList;
}

int main()
{
    BSTreeNode * pRoot = NULL;
    pHead = NULL;
    createBinarySearchTree(pRoot, 10);
    createBinarySearchTree(pRoot, 4);
    createBinarySearchTree(pRoot, 6);
    createBinarySearchTree(pRoot, 8);
    createBinarySearchTree(pRoot, 12);
    createBinarySearchTree(pRoot, 14);
    createBinarySearchTree(pRoot, 15);
    createBinarySearchTree(pRoot, 16);

	pHead = Convert(pRoot);
	//从最左侧开始打印双向链表
	cout << "从左向右打印:";
	DoubleList *p = pHead;
	while(p != NULL)
	{
		cout << p->m_nValue<<" ";
		p= p->m_pRight;
	}
	//从最右侧开始打印双向链表
	cout << endl <<"从右向左打印:";
	while(pHead->m_pRight != NULL)
	{
		pHead= pHead->m_pRight;
	}
	while(pHead != NULL)
	{
		cout << pHead->m_nValue<<" ";
		pHead = pHead->m_pLeft;
	}
	cout << endl;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值