zoukankan      html  css  js  c++  java
  • 左神算法书籍《程序员代码面试指南》——2_12将搜索二叉树转换成双向链表

    对二叉树的节点来说,有本身的值域,有指向左孩子和右孩子的两个指针;对双向链表的节点来说,有本身的值域,有指向上一个节点和下一个节点的指针。在结构上,两种结构有相似性,现在有一棵搜索二叉树,请将其转换为一个有序的双向链表。

     1 #include <iostream>
     2 #include <queue>
     3 using namespace std;
     4 struct treeNode
     5 {
     6     int v;
     7     treeNode *l, *r;
     8     treeNode(int a = -1) :v(a), l(nullptr), r(nullptr) {}
     9 };
    10 struct listNode
    11 {
    12     int v;
    13     listNode *pre, *next;
    14     listNode(int a = -1) :v(a), pre(nullptr), next(nullptr) {}
    15 };
    16 treeNode* root = new treeNode(6);
    17 listNode* head = new listNode(-1);
    18 queue<int>qD;
    19 void creatTree()
    20 {
    21     root->l = new treeNode(4);
    22     root->r = new treeNode(7);
    23     root->l->l = new treeNode(2);
    24     root->l->r = new treeNode(5);
    25     root->l->l->l = new treeNode(1);
    26     root->l->l->r = new treeNode(3);
    27     root->r->r = new treeNode(9);
    28     root->r->l = new treeNode(8);
    29 }
    30 void getData(treeNode* rt)
    31 {
    32     if (rt == nullptr)
    33         return;
    34     getData(rt->l);
    35     qD.push(rt->v);
    36     getData(rt->r);
    37 }
    38 void creatList()
    39 {
    40     listNode* p = head;
    41     while (!qD.empty())
    42     {
    43         listNode* q = new listNode(qD.front());
    44         qD.pop();
    45         p->next = q;
    46         q->pre = p;
    47         p = q;
    48     }
    49 }
    50 void printD()
    51 {
    52     listNode* p = head->next;
    53     while (p != nullptr)
    54     {
    55         cout << p->v << " ";
    56         p = p->next;
    57     }
    58 }
    59 int main()
    60 {
    61     creatTree();
    62     getData(root);
    63     creatList();
    64     printD();
    65     return 0;
    66 }
  • 相关阅读:
    Linux下忘记MySQL密码的解决办法
    Jenkins——为什么使用持续集成?
    JBoss7部署EJB连接MySQL
    同一进程中的线程有哪些资源可以共享(转)
    基于ssh开发web项目-用户登录流程
    mysql-5.6.16安装流程
    Spring学习笔记
    Hibernate持久化对象状态、转换方法和操作步骤
    Hibernate配置文件与关联映射介绍
    Java的hashCode方法
  • 原文地址:https://www.cnblogs.com/zzw1024/p/11444138.html
Copyright © 2011-2022 走看看