题解 | #二叉搜索树与双向链表#

二叉搜索树与双向链表

http://www.nowcoder.com/practice/947f6eb80d944a84850b0538bf0ec3a5

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};*/
class Solution {
public:
    vector<TreeNode*> v;
    TreeNode* Convert(TreeNode* pRootOfTree) {
         if (pRootOfTree == nullptr)
            return pRootOfTree;

        stack<TreeNode*> ss;
        TreeNode* p = pRootOfTree; //p is a Traversing pointer
        while(p || !ss.empty())
        {
            if(p){
                ss.push(p);
                p=p->left;
            }
            else{
                p = ss.top();
                ss.pop();

                v.push_back(p);
                p=p->right;
            }
        }
        v.front()->left = nullptr;
        v.back()->right = nullptr;
        for(int i=0;i<v.size()-1;i++)
        {
            v[i]->right=v[i+1];
            v[i+1]->left=v[i];
        }
//         v[v.size()-1]->left=v[v.size()-2];
        return v.front();
    }
};
全部评论

相关推荐

去B座二楼砸水泥地:不过也可以理解,这种应该没参加过秋招
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务