深感编程能力亟待提升,近期开始刷题库。
输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。题目:
不能创建任何新的结点,只调整指针的指向。要求:
本题收获:有关树的问题,可以考虑使用递归~
// 1:构造二元查找树;
// 2:中序遍历二元查找树,结点按从小到大顺序访问,假设之前访问过的结点已经调整为一个双向链表,那么
// 只需要将当前结点连接至双向链表的最后一个结点即可,访问结束,双向链表也就调整完了。
// ** 有关树的问题,常常可以考虑使用递归法。
#include<iostream>
using namespace std;
struct BSTreeNode
{
int value;
BSTreeNode *left;
BSTreeNode *right;
};
void addBSTreeNode(BSTreeNode *current, int value);
void inOrderBSTree(BSTreeNode *pBSTree);
void convertToDoubleList(BSTreeNode *current);
BSTreeNode *Head=NULL; //双向链表的头结点
BSTreeNode *Index=NULL; //记录当前链表中最后一个结点
int main()
{
BSTreeNode *root=NULL;
int i;
cout<<"Please input integers as value of BSTreeNode, (ctrl+z enter) to finish."<<endl;
while(cin>>i)
{
addBSTreeNode(root,i);
}
inOrderBSTree(root);
system("pause");
return 0;
}
/**********************************************************************/
void addBSTreeNode(BSTreeNode *current, int value) //函数需要改变指针值,故使用引用传递
{
if(current==NULL)
{
BSTreeNode *pBSTree=new BSTreeNode();
pBSTree->value=value;
pBSTree->left=NULL;
pBSTree->right=NULL;
current=pBSTree;
}
else if(current->value > value)
addBSTreeNode(current->left,value);
else if(current->value < value)
addBSTreeNode(current->right,value);
else
cout<<"This node already exists."<<endl;
}
/**********************************************************************/
/* 中序遍历二叉树,同时调整结点指针 */
void inOrderBSTree(BSTreeNode *pBSTree)
{
if(pBSTree==NULL)
return;
if(pBSTree->left!=NULL)
inOrderBSTree(pBSTree->left);
convertToDoubleList(pBSTree);
if(pBSTree->right!=NULL)
inOrderBSTree(pBSTree->right);
}
/**********************************************************************/
void convertToDoubleList(BSTreeNode *current)
{
current->left=Index;
if(Index==NULL)
Head=current;
else
Index->right=current;
Index=current;
cout<<current->value<<" ";
}