您的位置:首页 > 理论基础 > 数据结构算法

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

2017-12-27 16:19 381 查看
把二元查找树转变成排序的双向链表

 题目:

输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。

要求不能创建任何新的结点,只调整指针的指向。

   10

 / \

 6 14

 / \ / \

4 8 12 16

 转换成双向链表

4=6=8=10=12=14=16

#pragma warning(disable:4996)
#include <cstdio>
#include <cstring>
#define ll long long int
struct node
{
int data;
struct node* left = nullptr;
struct node* right = nullptr;
};
node* root = nullptr;
void Insert(node* nd,node* cur)
{
if(nd->data > cur->data)
{
if (cur->right == nullptr) cur->right = nd;
else Insert(nd, cur->right);
}
else
{
if (cur->left == nullptr) cur->left = nd;
else Insert(nd, cur->left);
}
}
void BuildTree(int n)
{
for(int i = 0; i < n; i++)
{
node* nd = new node;
scanf("%d", &nd->data);
if (root == nullptr) root = nd;
else Insert(nd, root);
}
}
node* GetLeft(node* nd)
{
if (nd == nullptr) return nullptr;
while (nd->left != nullptr) nd = nd->left;
return nd;
}
node * GetRight(node* nd)
{
if (nd == nullptr) return nullptr;
while (nd->right != nullptr) nd = nd->right;
return nd;
}
node* ToDLinkList(node * last,node * cur)
{
node* left = nullptr, *right = nullptr;
if (cur->left != nullptr) left = ToDLinkList(cur, cur->left);
if (cur->right != nullptr) right = ToDLinkList(cur, cur->right);
if (left != nullptr) left->right = cur;
if (right != nullptr) right->left = cur;
cur->left = left;
cur->right = right;
if(last != nullptr)
{
if (cur->data < last->data) return GetRight(cur);
else return GetLeft(cur);
}
return cur;
}
int main()
{
#ifdef local
//freopen("data.txt", "r", stdin);
#endif
int n;
scanf("%d", &n);
BuildTree(n);
root = ToDLinkList(nullptr, root);
root = GetLeft(root);
while (root != nullptr)
{
printf("%d ", root->data);
root = root->right;
}
printf("\n");
}


4=6=8=10=12=14=16
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据结构