剑指offer面试题27BST转换为有序双向链表

/*
这题目一看就是要递归 不能创建新节点
这到题目应该是我做这本书目前位置 最卡的一道题了。。想了好久。
但也怪自己浮躁把。
主要思想convert函数 main汉斯调用的函数 主要就是创建last变量 然后 最后返回头指针
convertnode 是重要的其实主要过程可以理解未一次中序遍历bst 得到有序的序列并且联系
每次输入一个指针 先把左边的弄好 然后last记录了左边的最后 再把last和根连接
然后last变成根 继续中序右子数 先到最左再和last连起来

*/
#include<iostream>
#include<cstdio>
using namespace std;

struct BinaryTreeNode
{
    int data;
    BinaryTreeNode * leftchild;
    BinaryTreeNode * rightchild;
    BinaryTreeNode(int t):data(t){};
};
BinaryTreeNode * CreateTree()
{
    BinaryTreeNode * root=new BinaryTreeNode(10);
    root->leftchild=new BinaryTreeNode(6);
    root->rightchild=new BinaryTreeNode(14);
    BinaryTreeNode * tmp=root->leftchild;
    tmp->leftchild=new BinaryTreeNode(4);
    tmp->rightchild=new BinaryTreeNode(8);
    tmp=root->rightchild;
    tmp->leftchild=new BinaryTreeNode(12);
    tmp->rightchild=new BinaryTreeNode(16);
    return root;
}
//这个递归函数完成整个链表的创建
/*
先左再中 后右 链接起来就行 用lastnode 记录 目前最后一个节点 然后后面再和这个链接
就是这样的思想
*/
void ConvertNode(BinaryTreeNode * root,BinaryTreeNode **lastnode)
{
    if(root==NULL) return ;
    BinaryTreeNode * p=root;
    if(p->leftchild!=NULL)
    ConvertNode(p->leftchild,lastnode);
    p->leftchild=*lastnode;
    if(*lastnode!=NULL)
    (*lastnode)->rightchild=p;
    *lastnode=p;
    if(p->rightchild!=NULL)
    ConvertNode(p->rightchild,lastnode);
}
BinaryTreeNode * Convert(BinaryTreeNode * root)
{
    BinaryTreeNode * last=NULL;
    ConvertNode(root,&last);
    //返回头指针
    BinaryTreeNode * head=last;
    while(head!=NULL && head->leftchild !=NULL)
    head=head->leftchild;
    return head;
}
void PrintList(BinaryTreeNode * head)
{
    while(head!=NULL)
    {
        printf("%d ",head->data);
        head=head->rightchild;
    }
}
int main()
{
    BinaryTreeNode * root=CreateTree();
    BinaryTreeNode * linklist=Convert(root);
    PrintList(linklist);
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值