将 BST 转换为排序的双向链表

Convert BST to Sorted Doubly Linked List

本文关键字:双向链表 排序 BST 转换      更新时间:2023-10-16

以下是我实现的将BST转换为排序双向链表的代码。但是对于以下输入,我缺少最右边的子分支

例如,对于输入 4 1 2 3 6 5 7(输入到 BST)

我缺少数据 2 和 3 的节点.Plz 告诉我代码有什么问题?

#include<iostream>
 using namespace std;
struct node
{
int data;
node* left;
node* right;
};
node* tree=NULL;
int count=1;
void inorder(node *tree)
{
if(tree!=NULL)
{
     inorder(tree->left);
    cout<<tree->data<<" ";
    inorder(tree->right);
}
}
node * insert(node *tree,int n)
{
if(tree==NULL)
{
    tree=new node;
    tree->left=tree->right=NULL;
    tree->data=n;
}
else if(tree->data>n)
tree->left=insert(tree->left,n);
else
tree->right=insert(tree->right,n);
return(tree);
}
node *start=NULL;
node *prev=NULL;
node * head=NULL;
void func(node *root)
{
if(root!=NULL)
{
    func(root->left);
    if(start==NULL)
    {
        start=root;
        start->left=NULL;
        start->right=NULL;
        prev=start;
        head=start;
        //cout<<start->data<<"  ";
    }
    else
    {
        start->right=root;
        start=start->right;
        start->left=prev;
        prev=start;
       // cout<<start->left->data<<"  ";
    }
    func(root->right);
}
}
int main()
{
int n;
cout<<"Enter the number of nodesn";
cin>>n;
int k=n;
int value;
while(n--)
{
   cin>>value; 
   tree=insert(tree,value);
}
inorder(tree);
cout<<endl;
func(tree);
cout<<endl;
while(head!=NULL)
{
    cout<<head->data<<"  ";
    head=head->right;
}
return 0;
}

您正在修改 func 中的原始树。例如,对于第一次调用funcstart->right = NULLfunc(root->right);在一起就没有意义了。您可以使用new分配内存并将节点复制到列表中,而不是执行start = root(和类似操作)。

问题出在func对于数据 = 1 的节点,将右侧子树覆盖为 NULL。并松开它