二叉搜索树与双向链表

题目描述

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

我的代码:

 1 class Solution {
 2     vector<TreeNode*> vec;
 3     void OrderTrace(TreeNode* pRoot)
 4     {
 5         if(!pRoot) return;
 6         OrderTrace(pRoot->left);
 7         vec.push_back(pRoot);
 8         OrderTrace(pRoot->right);
 9     }
10 public:
11     TreeNode* Convert(TreeNode* pRootOfTree)
12     {
13         if(!pRootOfTree)
14             return NULL;
15         OrderTrace(pRootOfTree);
16         int length = vec.size();
17         vec[0]->left = NULL;
18         for(int i = 0; i < length-1; i++)
19         {
20             vec[i]->right = vec[i+1];
21             vec[i+1]->left = vec[i];
22         }
23         vec[length - 1]->right = NULL;
24         return vec[0];
25     }
26 };

示例代码:

class Solution {
public:
    TreeNode* Convert(TreeNode* pRootOfTree)
    {
        if(pRootOfTree == nullptr) return nullptr;
        TreeNode* pre = nullptr;
         
        convertHelper(pRootOfTree, pre);
         
        TreeNode* res = pRootOfTree;
        while(res ->left)
            res = res ->left;
        return res;
    }
     
    void convertHelper(TreeNode* cur, TreeNode*& pre)
    {
        if(cur == nullptr) return;
         
        convertHelper(cur ->left, pre);
         
        cur ->left = pre;
        if(pre) pre ->right = cur;
        pre = cur;
         
        convertHelper(cur ->right, pre);
  
    }
};

 

posted @ 2018-04-21 22:00  Lune-Qiu  阅读(151)  评论(0编辑  收藏  举报