题目:
输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。
要求不能创建任何新的结点,只调整指针的指向。
10
/ \
6 14
/ \ / \
4 8 12 16
转换成双向链表
4=6=8=10=12=14=16。
要求不能创建任何新的结点,只调整指针的指向。
转换成双向链表
4=6=8=10=12=14=16。
我的解答:
#include "iostream"
using namespace std;
struct BSTreeNode
{
};
//插入函数
//由于可能root为NULL,所以可能会更改root。因此用指向指针的指针
//遇大向右,遇小向左
void insert(BSTreeNode **root,int value)
{
if(*root==NULL)
{
*root=new BSTreeNode;
(*root)->m_nValue=value;
(*root)->m_pLeft=NULL;
(*root)->m_pRight=NULL;
}
else
{
if (value <= (*root)->m_nValue)
{
insert(&((*root)->m_pLeft),value);
}
else
{
insert(&((*root)->m_pRight),value);
}
}
}
//这是不用指向指针的指针的方法。
//前提是已经有了根节点
//
void insert_no_pointer2pointer(BSTreeNode *root,int value)
{
BSTreeNode *node=new BSTreeNode;
node->m_nValue=value;
node->m_pLeft=NULL;
node->m_pRight=NULL;
if(value >= root->m_nValue)
{
if( root->m_pRight==NULL)
{
root->m_pRight=node;
return;
}
else
{
insert_no_pointer2pointer(root->m_pRight,value);
}
}
else if(value < root->m_nValue)
{
if (root->m_pLeft==NULL)
{
root->m_pLeft=node;
return;
}
else
{
insert_no_pointer2pointer(root->m_pLeft,value);
}
}
}
//显示函数,前序遍历
void display(BSTreeNode *root)
{
if(root==NULL)
{
return;
}
else
{
display(root->m_pLeft);
cout<<root->m_nValue<<endl;
display(root->m_pRight);
}
}
//将二叉搜索树变为双向链表
//输入为待转换的子树(或者全树)的根节点
//输出为已排列好的双向链表的最左节点
BSTreeNode* BStree2Doublelist(BSTreeNode* root)
{
if(!root->m_pLeft && !root->m_pRight)
return root;
else if (root->m_pLeft && root->m_pRight)
{
BSTreeNode* node=BStree2Doublelist(root->m_pLeft);
BSTreeNode* node1=BStree2Doublelist(root->m_pRight);
while(node->m_pRight)
{
node=node->m_pRight;
}
root->m_pLeft=node;
root->m_pRight=node1;
node->m_pRight=root;
node1->m_pLeft=root;
while (node->m_pLeft)
{
node=node->m_pLeft;
}
return node;
}
else if (!root->m_pLeft)
{
BSTreeNode* node2=BStree2Doublelist(root->m_pRight);
root->m_pRight=node2;
node2->m_pLeft=root;
return root;
}
else if(!root->m_pRight)
{
BSTreeNode* node3=BStree2Doublelist(root->m_pLeft);
while(node3->m_pRight)
{
node3=node3->m_pRight;
}
root->m_pLeft=node3;
node3->m_pRight=root;
while (node3->m_pLeft)
{
node3=node3->m_pLeft;
}
return node3;
}
else
{
cout<<"Error!!!"<<endl;
return NULL;
}
}
void main()
{
BSTreeNode *root=NULL;
insert(&root,10);
insert(&root,4);
insert(&root,12);
insert(&root,6);
insert(&root,14);
insert(&root,8);
insert(&root,16);
//display(root);
BSTreeNode* node=BStree2Doublelist(root);
cout<<node->m_nValue<<endl;
while (node->m_pRight)
{
node=node->m_pRight;
cout<<node->m_nValue<<endl;
}
cout<<endl;
}