题目:输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
#include<iostream>
using namespace std;
struct BinaryTreeNode
{
int val;
BinaryTreeNode* left;
BinaryTreeNode* right;
};
void ConvertNode(BinaryTreeNode* pNode, BinaryTreeNode** pLastNodeInList);
BinaryTreeNode* CreateTreeNode(int val)
{
BinaryTreeNode* pNode = new BinaryTreeNode;
pNode->val = val;
pNode->left = nullptr;
pNode->right = nullptr;
return pNode;
}
//连接结点
void Connect(BinaryTreeNode* pRoot, BinaryTreeNode* left, BinaryTreeNode* right)
{
if (pRoot != nullptr)
{
pRoot->left = left;
pRoot->right = right;
}
}
//释放结点
void DestroyTree(BinaryTreeNode* pRoot)
{
if (pRoot != nullptr)
{
BinaryTreeNode* pLeft = pRoot->left;
BinaryTreeNode* pRight = pRoot->right;
delete pRoot;
pRoot = nullptr;
DestroyTree(pLeft);
DestroyTree(pRight);
}
}
BinaryTreeNode* Convert(BinaryTreeNode* pRoot)
{
BinaryTreeNode* pLastNodeInList = nullptr;
ConvertNode(pRoot, &pLastNodeInList);
//pLastNodeInList返回的是链表最后一个结点,需要返回第一个结点
BinaryTreeNode* pHeadOfList = pLastNodeInList;
while (pHeadOfList != nullptr&&pHeadOfList->left != nullptr)
pHeadOfList = pHeadOfList->left;
return pHeadOfList;
}
void ConvertNode(BinaryTreeNode* pNode, BinaryTreeNode** pLastNodeInList)
{
if (pNode == nullptr)
return;
BinaryTreeNode* pCurrent = pNode;
//判断当前结点是否有左结点,有的话遍历它的左结点
if (pCurrent->left != nullptr)
ConvertNode(pCurrent->left, pLastNodeInList);
//如果没有左结点,则把当前结点和它的前一个结点(即左结点)互相连接
pCurrent->left = *pLastNodeInList;
if (*pLastNodeInList != nullptr)
(*pLastNodeInList)->right = pCurrent;
*pLastNodeInList = pCurrent;
//判断当前结点有没有右结点,有的话则继续连接右结点
if (pCurrent->right != nullptr)
ConvertNode(pCurrent->right, pLastNodeInList);
}
void PrintRight(BinaryTreeNode* pRoot)
{
if (pRoot != nullptr)
{
BinaryTreeNode* pNode = pRoot;
while (pNode != nullptr)
{
printf("%d\t", pNode->val);
pNode = pNode->right;
}
}
}
int main()
{
BinaryTreeNode* pNode1 = CreateTreeNode(1);
BinaryTreeNode* pNode2 = CreateTreeNode(2);
BinaryTreeNode* pNode3 = CreateTreeNode(3);
BinaryTreeNode* pNode4 = CreateTreeNode(4);
BinaryTreeNode* pNode5 = CreateTreeNode(5);
BinaryTreeNode* pNode6 = CreateTreeNode(6);
BinaryTreeNode* pNode7 = CreateTreeNode(7);
BinaryTreeNode* pNode8 = CreateTreeNode(8);
BinaryTreeNode* pNode9 = CreateTreeNode(9);
Connect(pNode5, pNode3, pNode7);
Connect(pNode3, pNode2, pNode4);
Connect(pNode2, pNode1, nullptr);
Connect(pNode7, pNode6, pNode8);
Connect(pNode8, nullptr, pNode9);
BinaryTreeNode* pHead = Convert(pNode5);
PrintRight(pHead);
DestroyTree(pNode1);
return 0;
}