首页 > 技术文章 > 剑指offer---二叉搜索树与双向链表

iwangzhengchao 2018-10-30 13:29 原文

题目二叉搜索树与双向链表

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

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};*/
class Solution {
public:
    TreeNode* Convert(TreeNode* pRootOfTree)
    {
        
    }
};

 

解题代码:

 1 class Solution {
 2 public:
 3     TreeNode* Convert(TreeNode* pRootOfTree) {
 4         // pLastNodeInList 指向双向链表的最后一个节点
 5         TreeNode* pLastNodeInList = nullptr;
 6         ConvertNode(pRootOfTree, pLastNodeInList);
 7 
 8         // 返回双向链表的头结点
 9         TreeNode* pHeadOfList = pLastNodeInList;
10         while(pHeadOfList != nullptr && pHeadOfList->left != nullptr)
11             pHeadOfList = pHeadOfList->left;
12         return pHeadOfList;
13     }
14 
15 private:
16     void ConvertNode(TreeNode* pNode, TreeNode * &pLastNodeInList){
17         if(pNode == nullptr)
18             return ;
19 
20         TreeNode* pCurrent = pNode;
21         if(pCurrent->left != nullptr)
22             ConvertNode(pCurrent->left, pLastNodeInList);
23 
24         pCurrent->left = pLastNodeInList;
25         // 若此时链表含有节点,则将链表最后一个节点的右指针指向pCurrent节点
26         if(pLastNodeInList != nullptr)
27             pLastNodeInList->right = pCurrent;
28         // 更新指向链表最后一个节点的指针
29         pLastNodeInList = pCurrent;
30 
31         if(pCurrent->right != nullptr)
32             ConvertNode(pCurrent->right, pLastNodeInList);
33     }
34 };

 

推荐阅读