1.把二元查找树转变成排序的双向链表(树)

来源:互联网 发布:华山 长空栈道 知乎 编辑:程序博客网 时间:2024/06/06 18:03
1.把二元查找树转变成排序的双向链表(树)
 题目:
输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。
要求不能创建任何新的结点,只调整指针的指向。
   10
  / /
  6  14
 / / / /
4  8 12 16
 转换成双向链表
4=6=8=10=12=14=16。
 
 首先我们定义的二元查找树 节点的数据结构如下:
 struct BSTreeNode
{
  int m_nValue; // value of node
  BSTreeNode *m_pLeft; // left child of node
  BSTreeNode *m_pRight; // right child of node
};
 





//coder:Lee
//note:一、条件,判断是否为空,二、首节点特殊处理,三、该添加&就添加,应用不分配内存
#include<iostream>
using namespace std;
struct BSTreeNode
{
BSTreeNode* m_pLeft;
BSTreeNode* m_pRight;
int m_nValue;
};
void InitBSTree(BSTreeNode *& root)
{
int i;
cin>>i;
if (i!=0)
{
root=new BSTreeNode();
root->m_nValue=i;
InitBSTree(root->m_pLeft);
InitBSTree(root->m_pRight);
}
else
{


root=NULL;
}


return;
}
void PreTraverse(BSTreeNode* root)
{
if(!root)
return;
else
{
cout<<root->m_nValue<<"  ";
PreTraverse(root->m_pLeft);
PreTraverse(root->m_pRight);
}


}
const LEFT=1;
const RIGHT=2;


BSTreeNode* BSTreeToLink(BSTreeNode* root,int Direct)
{
if (!root)
{
return NULL;
}
BSTreeNode* PreNode=BSTreeToLink(root->m_pLeft,RIGHT);//取左子树的最大节点
BSTreeNode* NextNode=BSTreeToLink(root->m_pRight,LEFT);//取右子树的最小节点
//将三个节点相连,如果其他两个非空的话
if (PreNode)
PreNode->m_pRight=root;
root->m_pLeft=PreNode;
root->m_pRight=NextNode;
if (NextNode)
NextNode->m_pLeft=root;
if (Direct==LEFT)//定位最小的
while (root->m_pLeft!=NULL)
root=root->m_pLeft;
if (Direct==RIGHT) //定位最大的
while (root->m_pRight!=NULL)
root=root->m_pRight;
return root;
}
int IsFirstArrive=1;
BSTreeNode* pHead,*pLast;
void NewBSTreeToLink(BSTreeNode* root)//通过中序遍历
{
if (!root)
return;
if(root->m_pLeft!=NULL)
NewBSTreeToLink(root->m_pLeft) ;
else
{
if(IsFirstArrive==1)//找到首节点
{
cout<<"FirstArriver"<<endl;
pHead=root;
pLast=root;
IsFirstArrive=0;
}
}
if (root!=pHead)//非首节点,则将本节点与上一节点相连
{
root->m_pLeft=pLast;
pLast->m_pRight=root;
pLast=root;
cout<<"value:"<<root->m_nValue<<endl;
}
if(root->m_pRight!=NULL)
NewBSTreeToLink(root->m_pRight);
else
return;
}
int main()
{
BSTreeNode *root;
InitBSTree(root);//叶子节点输入0
PreTraverse(root);
cout<<endl;
/* BSTreeNode *head=BSTreeToLink(root,LEFT);//方法一


while (head)
{
cout<<head->m_nValue<<endl;
head=head->m_pRight;
}
*/


NewBSTreeToLink(root);//方法二
while (pHead->m_pRight!=NULL)//定位到链表尾,
pHead=pHead->m_pRight;
while(pHead)//逆向输出
{
cout<<pHead->m_nValue<<endl;
pHead=pHead->m_pLeft;
}




return 0;
}
原创粉丝点击