当前位置:编程学习 > C/C++ >>

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

\\

#include "stdafx.h"
#include <iostream>
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 nNodeValue = 0;
	cin >> nNodeValue;	
	if (-1 == nNodeValue)
	{
		pRoot = NULL;
		return; 
	}
	else
	{
		pRoot = new BinaryTreeNode();
		pRoot->m_nValue = nNodeValue;
		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;
}

 

补充:软件开发 , C++ ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,