题目:
把二叉查找树变成排序后的双向链表.
10
/ \
6 14
/ \ / \
4 8 12 16
得到 4=6=8=10=12=14=16
思路:
由于对二叉查找树的中序遍历就会得到一个排序后的数组。
所以可以在中序遍历时对每个遍历的结点进行构建双向链表(注意不是循环链表),每次对遍历的结点进行插入操作,最终得到结果。代码如下:
#include <iostream>
using namespace std;
struct BinarySearchTreeNode
{
int data;
BinarySearchTreeNode *left,*right;
};
typedef BinarySearchTreeNode DoubleList;
DoubleList *head=NULL,*tail=NULL; //双向链表头尾指针
//利用依次插入结点构造二叉查找树
void InsertNode(BinarySearchTreeNode *&root,int key)
{
if(!root)
{
BinarySearchTreeNode *newnode=new BinarySearchTreeNode;
newnode->left=newnode->right=NULL;
newnode->data=key;
root=newnode;
}
else
{
if(key<root->data)
InsertNode(root->left,key);
else if(key>root->data)
InsertNode(root->right,key);
else if(key==root->data)
cout<<"树中已有该结点"<<endl;
}
}
void Convert(DoubleList *cur)
{
if(!tail)
{
head=cur;
cur->left=tail;
}
else
{
cur->left=tail;
tail->right=cur;
}
tail=cur;
}
//中序遍历二叉查找树
void PostOrder(BinarySearchTreeNode *root)
{
if(root)
{
PostOrder(root->left);
Convert(root);
PostOrder(root->right);
}
}
int main()
{
int a[7]={10,6,8,4,12,14,16};
BinarySearchTreeNode *root=new BinarySearchTreeNode;
root=NULL;
for(int i=0;i<7;++i)
InsertNode(root,a[i]);
PostOrder(root);
while (head!=NULL) //从前往后的次序
{
cout<<head->data<<" ";
head=head->right;
}
cout<<endl;
while (tail!=NULL) //从后往前的次序
{
cout<<tail->data<<" ";
tail=tail->left;
}
system("pause");
return 0;
}
本文详细介绍了如何将二叉查找树转换为排序后的双向链表的过程,通过中序遍历实现链表构建。
2792

被折叠的 条评论
为什么被折叠?



