1.把2叉查找树转换成双向链表
参考线索二叉树的建立方法,对二叉查找树进行中序遍历,遍历中保存1个pre指针,指向刚刚访问过的节点,即当前节点的中序前驱。
代码如下:
#include<iostream>
#include<cstdlib>
using namespace std;
typedef struct node
{
int data;
struct node* left;
struct node* right;
}Tree;
//输入二叉查找树的先序顺序,NULL指针用0代替
Tree* create(void)
{
int d;
Tree *root=NULL;
//按先序输入,NULL指针是0
cin>>d;
if(d==0)
return NULL;
else
{
root=(Tree*)malloc(sizeof(Tree));
root->data=d;
root->left=create();
root->right=create();
}
return root;
}
//参考线索二叉树
Tree* pre=NULL;
void inorder2(Tree* t)
{
if(t)
{
Tree* left=t->left;
Tree* right=t->right;
inorder2(left);
t->left=pre;
if(pre!=NULL)
pre->right=t;
pre=t;
inorder2(right);
}
}
//遍历这个双向链表
void bianli(Tree* t)
{
while(t->left!=NULL)
t=t->left;
Tree* temp=t;
while(temp!=NULL)
{
cout<<temp->data<<" ";
temp=temp->right;
}
cout<<endl;
}
void del(Tree* t)
{
Tree *pre=NULL;
while(t->left!=NULL)
t=t->left;
while(t)
{
pre=t;
t=t->right;
free(pre);
}
} int main(void) { Tree* root=NULL; root=create(); inorder2(root); bianli(root);
del(root);
return 0; }
例子输入: 输入 10 6 4 0 0 8 0 0 14 12 0 0 16 0 0建立树,输出结果是4 6 8 10 12 14 16
试的另外一种方法,即在中序递归通过查找节点的中序前驱和中序后继,然后改变节点left和right指针值,这是错误的,因为中序中,后面的节点可能会用到前面节点的left,right孩子信息去找前驱或后继。
浙公网安备 33010602011771号