码迷,mamicode.com
首页 > 其他好文 > 详细

二叉搜索树与双向链表

时间:2018-04-21 22:30:52      阅读:266      评论:0      收藏:0      [点我收藏+]

标签:ace   搜索   tor   col   ++   vector   class   for   代码   

我的代码:

 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);
         
         
         
    }
};

 

二叉搜索树与双向链表

标签:ace   搜索   tor   col   ++   vector   class   for   代码   

原文地址:https://www.cnblogs.com/Lune-Qiu/p/8903985.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!