首页 > 其他 > 详细

二叉搜索树与双向链表

时间:2018-04-21 22:16:11      阅读:254      评论:0      收藏:0      [点我收藏+]

我的代码:

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

 

二叉搜索树与双向链表

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!