36. 二叉搜索树与双向链表

https://www.nowcoder.com/practice/947f6eb80d944a84850b0538bf0ec3a5?tpId=13&tqId=11179&tPage=1&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking&from=cyc_github&tab=answerKey
Convert定义:将pRootOfTree为根节点的树双向链表化,并返回第一个链表节点。

class Solution {
public:
    TreeNode* Convert(TreeNode* pRootOfTree) {
        TreeNode* it;
        if(pRootOfTree == nullptr) return nullptr;
        if(pRootOfTree->left == nullptr && pRootOfTree->right == nullptr){
            return pRootOfTree;
        }
        TreeNode* leftHead;
        if(pRootOfTree->left != nullptr){
            leftHead = Convert(pRootOfTree->left);
            auto it = leftHead;
            while(it->right){
                it = it->right;
            }
            pRootOfTree->left = it;
            it->right = pRootOfTree;
        }
        if(pRootOfTree->right != nullptr){
            it = Convert(pRootOfTree->right);
            it->left = pRootOfTree;
            pRootOfTree->right = it;
            //如果leftHead没有被赋值,要记得赋值
            if(pRootOfTree->left == nullptr){
                leftHead = pRootOfTree;
            }
        }
        return leftHead;
        
    }
};
//额外空间
class Solution {
public:
    vector<TreeNode*> tmp;
    void mid(TreeNode* pRootOfTree){
        if(pRootOfTree == nullptr){
            return ;
        }
        mid(pRootOfTree->left);
        tmp.push_back(pRootOfTree);
        mid(pRootOfTree->right);
    }
    TreeNode* Convert(TreeNode* pRootOfTree) {
        if(pRootOfTree == nullptr){
            return nullptr;
        }
        if(pRootOfTree->left == nullptr && pRootOfTree->right == nullptr){
            return pRootOfTree;
        }
        mid(pRootOfTree);
        for(int i=0;i<tmp.size();++i){
            if(i==0){
                tmp[i]->left = nullptr;
                tmp[i]->right = tmp[i+1];
            }else if(i== tmp.size()-1){
                tmp[i]->left = tmp[i-1];
                tmp[i]->right = nullptr;
            }else{
                tmp[i]->left = tmp[i-1];
                tmp[i]->right = tmp[i+1];
            }
        }
        return tmp[0];
    }
};
posted @ 2021-03-28 16:43  rxh1999  阅读(35)  评论(0编辑  收藏  举报