找回密码
 立即注册→加入我们

QQ登录

只需一步,快速开始

搜索
热搜: 下载 VB C 实现 编写
查看: 2550|回复: 1

算法题-二叉树转双向链表

[复制链接]

311

主题

228

回帖

7377

积分

用户组: 真·技术宅

UID
2
精华
76
威望
291 点
宅币
5623 个
贡献
253 次
宅之契约
0 份
在线时间
954 小时
注册时间
2014-1-25
发表于 2014-4-17 17:50:38 | 显示全部楼层 |阅读模式

欢迎访问技术宅的结界,请注册或者登录吧。

您需要 登录 才可以下载或查看,没有账号?立即注册→加入我们

×
1.把二元查找树转变成排序的双向链表
题目:
输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。
要求不能创建任何新的结点,只调整指针的指向。
     10
    / \
   6  14
  / \ / \
4  8 12 16
转换成双向链表
4=6=8=10=12=14=16。

首先我们定义的二元查找树 节点的数据结构如下:
  1. struct BSTreeNode
  2. {
  3.     int m_nValue; // value of node
  4.     BSTreeNode *m_pLeft; // left child of node
  5.     BSTreeNode *m_pRight; // right child of node
  6. };
复制代码
我的解法
  1. #include <stdio.h>

  2. struct BSTreeNode
  3. {
  4.     int m_nValue;
  5.     BSTreeNode* m_pLeft;//prev
  6.     BSTreeNode* m_pRight;//next
  7. };

  8. BSTreeNode* addnode(int value,BSTreeNode* left=NULL,BSTreeNode* right=NULL)
  9. {
  10.     BSTreeNode* newone=new BSTreeNode;
  11.     newone->m_pLeft=NULL;
  12.     newone->m_pRight=NULL;
  13.     newone->m_nValue=value;
  14.     if(left)
  15.     {
  16.         newone->m_pLeft=left;
  17.     }
  18.     if(right)
  19.     {
  20.         newone->m_pRight=right;
  21.     }
  22.     return newone;
  23. }

  24. BSTreeNode* prevone=NULL;

  25. void findone(BSTreeNode* curone)//中序遍历
  26. {
  27.     if(curone->m_pLeft)
  28.     {
  29.         findone(curone->m_pLeft);
  30.     }

  31.     prevone->m_pRight=curone;
  32.     curone->m_pLeft=prevone;
  33.     prevone=curone;

  34.     if(curone->m_pRight)
  35.     {
  36.         findone(curone->m_pRight);
  37.     }
  38. }

  39. void deletelist(BSTreeNode* head)
  40. {
  41.     if(head->m_pRight)
  42.     {
  43.         deletelist(head->m_pRight);
  44.     }
  45.     delete head;
  46. }

  47. void showlist(BSTreeNode* head)
  48. {
  49.     while(head->m_pRight)
  50.     {
  51.         printf("%d ",head->m_pRight->m_nValue);
  52.         head=head->m_pRight;
  53.     }
  54.     printf("\n");
  55. }

  56. int main(int argc, char* argv[])
  57. {
  58.     BSTreeNode* head=addnode(-1);
  59.     head->m_pLeft=NULL;
  60.     prevone=head;

  61.     BSTreeNode* root=addnode(10,addnode(6,addnode(4),addnode(8)),addnode(14,addnode(12),addnode(16)));
  62.     findone(root);

  63.     prevone->m_pRight=NULL;
  64.     showlist(head);

  65.     return 0;
  66. }
复制代码

回复

使用道具 举报

1113

主题

1654

回帖

7万

积分

用户组: 管理员

一只技术宅

UID
1
精华
245
威望
744 点
宅币
24306 个
贡献
46222 次
宅之契约
0 份
在线时间
2302 小时
注册时间
2014-1-26
发表于 2014-4-17 21:03:08 | 显示全部楼层
每次都是我来排版。。。
回复 赞! 靠!

使用道具 举报

QQ|Archiver|小黑屋|技术宅的结界 ( 滇ICP备16008837号 )|网站地图

GMT+8, 2024-5-16 12:11 , Processed in 0.038028 second(s), 32 queries , Gzip On.

Powered by Discuz! X3.5

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表