随笔 - 147  文章 - 5  评论 - 6  阅读 - 81298

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)<br>{<br>  Tree *pre=NULL;<br>  <br>  while(t->left!=NULL)<br>    t=t->left;<br>  while(t)<br>  {<br>    pre=t;<br>    t=t->right;<br>    free(pre);<br>  }<br>}
 
int main(void)
{
    Tree* root=NULL;
    root=create();
 
    inorder2(root);
    bianli(root);
      <br>     del(root);<br>
    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孩子信息去找前驱或后继。

posted on   紫金树下  阅读(202)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示