将 BST 转换为排序的双向链表
Convert BST to Sorted Doubly Linked List
以下是我实现的将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
中的原始树。例如,对于第一次调用func
,start->right = NULL
和func(root->right);
在一起就没有意义了。您可以使用new
分配内存并将节点复制到列表中,而不是执行start = root
(和类似操作)。
问题出在func
对于数据 = 1 的节点,将右侧子树覆盖为 NULL。并松开它
相关文章:
- 如何实现 Front() 方法以返回模板化双向链表C++的第一个元素?
- 如何实现容纳整数和无效指针的双向链表?
- 为什么我的双向链表删除函数会删除多个节点?
- 我对数据结构、双向链表有一些问题
- C++ 双向链表:使用矩阵类成员创建和填充列表
- 在 c++ 中具有向量的双向链表构造函数
- 如何在双向链表上实现复制赋值?
- 在C++中删除双向链表的头节点后出现访问冲突异常
- 在双向链表中实现 Popback
- 在C++中反转双向链表
- 双向链表 - 无法删除第一个节点
- 我当前实现的双向链表类是否需要重构迭代器 end() 功能?
- 双向链表 std::unique_ptr 类在节点删除时无法按预期工作
- C++ 双向链表 - 插入同时保持递增顺序
- 如何找到双向链表的最大元素?
- 对双向链表进行排序会产生运行时错误
- 如何在双向链表C++上使用插入排序
- 将 BST 转换为排序的双向链表
- 实现排序的双向链表的困难
- 双向链表气泡排序,反向方法现已中断