以下是我实现的将 BST 转换为排序双向链表的代码。但是对于以下输入,我缺少最左最右的子分支
例如。用于输入 4 1 2 3 6 5 7(输入到 BST)
我缺少数据 2 和 3 的节点。请告诉我代码有什么问题?
#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 nodes\n";
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;
}