7. 重建二叉树

class Solution {
public:
    TreeNode* f(vector<int>& pre, int pleft, int pright, vector<int>& vin, int vleft, int vright){
        if(pleft>pright) return nullptr;
        int rootVal = pre[pleft];
        TreeNode* root = new TreeNode(rootVal);

        vector<int>::iterator rootInVin;
        rootInVin = find(vin.begin()+vleft, vin.begin()+vright, rootVal);
        //vin l l l l rootInVin r r r
        int leftlen = rootInVin - (vin.begin()+vleft);
        //lpl: left节点的pre的left
        int lpl = pleft +1 ;
        //lpr: left节点的pre的right
        int lpr = lpl + leftlen-1;
        //注意lpr到rpl之间是+1
        int rpl = lpr + 1;
        int rpr = pright;
        int lvl = vleft;
        int lvr = lvl + leftlen -1;
        int rvl = lvr+2;
        int rvr = vright;
        root->left = f(pre, lpl, lpr, vin, lvl, lvr);
        root->right = f(pre, rpl, rpr, vin, rvl, rvr);
        return root;
    }
    TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
        return f(pre, 0, pre.size()-1, vin, 0, vin.size()-1);
    }
};
class Solution {
public:
    TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
        //候选节点为空
        if(vin.size() == 0){
            return nullptr;
        }
        //找到pre中第一个在vin中出现的节点,就是vin中所有节点的根节点
        vector<int>::iterator rootInVin;
        for(auto& scan: pre){
            rootInVin = find(vin.begin(), vin.end(), scan);
            if(rootInVin != vin.end()){
                break;
            }
        }
        TreeNode* root = new TreeNode(*rootInVin);
        vector<int> nextpre{pre.begin()+1, pre.end()};
        vector<int> nextleft {vin.begin(), rootInVin};
        vector<int> nextright{rootInVin+1, vin.end()};
        root->left = reConstructBinaryTree(nextpre, nextleft);
        root->right = reConstructBinaryTree(nextpre, nextright);
        return root;
    }
};
posted @ 2021-03-28 11:29  rxh1999  阅读(27)  评论(0编辑  收藏  举报