首页 > 代码库 > 剑指offer 6 重建二叉树

剑指offer 6 重建二叉树

不用迭代器的代码

class Solution {
public:
    TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
        TreeNode* root = NULL;
        int length_pre = pre.size();
        int length_vin = vin.size();
        if(length_pre <= 0 || length_vin <= 0)
            return root;
        return ConstructCore(pre,vin,0,length_pre-1,0,length_vin-1);
    }
    TreeNode* ConstructCore(vector<int> pre,vector<int> vin,int start_pre,int end_pre,int start_vin,int end_vin){
        int rootval = pre[start_pre];
        TreeNode* root = new TreeNode(rootval);
        if(start_pre == end_pre || start_vin == end_vin)
            return root;
        int mid;
        for(int i = start_vin;i <= end_vin;i++){
            if(pre[start_pre] == vin[i]){
                mid = i;
                break;
            }
        }
        if(mid > start_vin)
            root->left = ConstructCore(pre,vin,start_pre+1,mid-start_vin+start_pre,start_vin,mid-1);
        if(end_vin > mid)
            root->right = ConstructCore(pre,vin,mid-start_vin+start_pre+1,end_pre,mid+1,end_vin);
        return root;
    }
};

 

剑指offer 6 重建二叉树