二叉搜索树与双向链表 【微软面试100题 第一题】

题目要求:输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。

参考题目:剑指offer第27题

解决思路:

  1. 根据观察可知,双向链表顺序即为二叉树的中序遍历结果----->采用中序遍历+递归;

  2. 中序遍历顺序为:左+中+右,传入一个变量pre。

    pre可以这样理解:当前结点的pre就是当前结点的前驱。如结点6的前驱是4,结点10的前驱是8.结点4的前驱是NULL。

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include <iostream>
 
using namespace std;
 
typedef struct BinaryTree
{
    struct BinaryTree *left,*right;
    int data;
}BinaryTree;
 
void initTree(BinaryTree **p);
void printList(BinaryTree *list);
BinaryTree *treeToList(BinaryTree *pTree);
 
int main(void)
{
    BinaryTree *pTree = NULL,*pList = NULL;
 
    initTree(&pTree);
    pList = treeToList(pTree);
    printList(pList);
    return 0;
}
//      1
//     / \
//    2   3
//   / \
//  4   5
void initTree(BinaryTree **p)
{
    *p = new BinaryTree;
    (*p)->data = 1;
 
    BinaryTree *tmpNode = new BinaryTree;
    tmpNode->data = 2;
    (*p)->left = tmpNode;
 
    tmpNode = new BinaryTree;
    tmpNode->data = 3;
    (*p)->right = tmpNode;
    tmpNode->left = NULL;
    tmpNode->right = NULL;
 
    BinaryTree *currentNode = (*p)->left;
 
    tmpNode = new BinaryTree;
    tmpNode->data = 4;
    currentNode->left = tmpNode;
    tmpNode->left = NULL;
    tmpNode->right = NULL;
 
    tmpNode = new BinaryTree;
    tmpNode->data = 5;
    currentNode->right = tmpNode;
    tmpNode->left = NULL;
    tmpNode->right = NULL;
 
}
void printList(BinaryTree *list)
{
    while(list!=NULL)
    {
        cout << list->data;
        if(list->right!=NULL)
        {
            cout << "<==>";
        }
        list = list->right;
    }
}<br>//---------------核心代码-----------------------
void convert(BinaryTree *pTree,BinaryTree **pre)
{
    if(pTree == NULL)
        return;
    BinaryTree *pCurrent = pTree;
    if(pCurrent->left != NULL)
        convert(pTree->left,pre);
 
    //当前点的前驱为pre
    pCurrent->left = *pre;
    //pre不为NULL,pre的后继为当前点
    if(*pre != NULL)
        (*pre)->right = pCurrent;
    //pre为当前点
    *pre = pCurrent;
 
    if(pCurrent->right != NULL)
        convert(pTree->right,pre);
}
BinaryTree *treeToList(BinaryTree *pTree)
{
    BinaryTree *pre = NULL;
 
    convert(pTree,&pre);
 
    //按照初始化的树,链表为4<==>2<==>5<==>1<==>3
    //此时pre在结点3处,应该返回到结点4处,再遍历输出
    while(pre!=NULL && pre->left!=NULL)
        pre = pre->left;
 
    return pre;
}

  

posted on   tractorman  阅读(600)  评论(1编辑  收藏  举报

编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?

导航

统计

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