程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> 面試題24:二叉搜索樹與雙向鏈表

面試題24:二叉搜索樹與雙向鏈表

編輯:C++入門知識

\\

#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;
}

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved