简体   繁体   中英

I am getting an error in my code. Problem:Construct Binary Tree from Preorder and Inorder Traversal

Given preorder and inorder traversal of a tree, construct the binary tree. For Example: preorder = [3,9,20,15,7] inorder = [9,3,15,20,7]

Return the binary tree.

My code is given below:

//helper function
TreeNode* build(vector<int> &preorder, vector<int> &inorder, int start, int end)
{
    static int index = 0;
    if(start>end)
        return NULL;
    TreeNode *root = new TreeNode(preorder[index++]);  //new node creation
    if(start == end)  // if no element left, then return
        return root;
    int preindex = binary_search(inorder.begin(),inorder.end(),root->val);  //find the position of root for new iteration
    root->left = build(preorder,inorder,start,preindex-1);  // recur for left
    root->right = build(preorder,inorder,preindex+1,end);   // recur for right
    return root;  // return root
}

TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
    int start=0;
    int end=preorder.size()-1;
    return build(preorder,inorder,start,end); // call for helper function   
} 

The above code is showing error saying =ERROR: AddressSanitizer: heap-buffer-overflow on address 0x603000000030 at pc 0x000000382d77 bp 0x7ffc26698900 sp 0x7ffc266988f8

Please help me guys. Thanks in advance.

二分搜索仅适用于已排序的对象,并且似乎没有对中序向量进行排序。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM