面试题24:二叉搜索树与双向链表

2014-11-23 22:25:59 · 作者: · 浏览: 7

\\

#include "stdafx.h"
#include 
using namespace std;

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

void Convert(BinaryTreeNode *pRoot, BinaryTreeNode *&pLastInList)
{
	if (pRoot == NULL)
	{
		return;
	}

	BinaryTreeNode *pCurrentNode = pRoot;

	if (pCurrentNode->m_pLeft != NULL)
	{
		Convert(pCurrentNode->m_pLeft, pLastInList);
	}

	pCurrentNode->m_pLeft = pLastInList;
	if (pLastInList != NULL)
	{
		pLastInList->m_pRight = pCurrentNode;	
	}	
	pLastInList = pCurrentNode;

	if (pCurrentNode->m_pRight != NULL)
	{
		Convert(pCurrentNode->m_pRight, pLastInList);
	}	
}

BinaryTreeNode *ConvertBSTToDoubleList(BinaryTreeNode *pRoot)
{
	if (pRoot == NULL)
	{
		return NULL;
	}

    BinaryTreeNode *pLastInList = NULL;//指向排好序的双向链表的最后一个结点
	Convert(pRoot, pLastInList);
	while (pLastInList->m_pLeft != NULL)//返回到头结点
	{
		pLastInList = pLastInList->m_pLeft;
	}
	return pLastInList;
}

//以先序的方式构建二叉树,输入-1表示结点为空
void CreateBinaryTree(BinaryTreeNode *&pRoot)
{
	int nNodeva lue = 0;
	cin >
> nNodeva lue; if (-1 == nNodeva lue) { pRoot = NULL; return; } else { pRoot = new BinaryTreeNode(); pRoot->m_nValue = nNodeva lue; CreateBinaryTree(pRoot->m_pLeft); CreateBinaryTree(pRoot->m_pRight); } } void PrintInOrder(BinaryTreeNode *&pRoot)//中序遍历二叉树 { if (pRoot != NULL) { PrintInOrder(pRoot->m_pLeft); cout << pRoot->m_nValue << " "; PrintInOrder(pRoot->m_pRight); } } void PrintDoubleListFromLeftToRight(BinaryTreeNode *pRoot)//从左到右打印双向链表 { if (pRoot == NULL) { return; } BinaryTreeNode *pNode = pRoot; while (pNode != NULL) { cout << pNode->m_nValue << " "; pNode = pNode->m_pRight; } cout << endl; } void PrintDoubleListFromRightToLeft(BinaryTreeNode *pRoot)//从右向左打印双向链表 { if (pRoot == NULL) { return; } BinaryTreeNode *pNode = pRoot; while (pNode->m_pRight != NULL) { pNode = pNode->m_pRight; } while (pNode != NULL) { cout << pNode->m_nValue << " "; pNode = pNode->m_pLeft; } cout << endl; } int _tmain(int argc, _TCHAR* argv[]) { BinaryTreeNode *pRoot = NULL; CreateBinaryTree(pRoot); PrintInOrder(pRoot);//4 6 8 10 12 14 16 cout << endl; BinaryTreeNode *pDoubleListHead = ConvertBSTToDoubleList(pRoot); PrintDoubleListFromLeftToRight(pDoubleListHead);//4 6 8 10 12 14 16 PrintDoubleListFromRightToLeft(pDoubleListHead);//16 14 12 10 8 6 4 system("pause"); return 0; }