微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

我的代码中出现错误问题:从预序和有序遍历构造二叉树

如何解决我的代码中出现错误问题:从预序和有序遍历构造二叉树

给出一棵树的前序和有序遍历,构造二叉树。 例如: 预购= [3,9,20,15,7] 顺序= [9,3,7]

返回二叉树。

我的代码如下:

//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,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,end); // call for helper function   
} 

上面的代码显示错误提示 =错误:AddressSanitizer:PC 0x000000382d77 bp 0x7ffc26698900 sp 0x7ffc266988f8在地址0x603000000030上的堆缓冲区溢出

请帮助我。预先感谢。

解决方法

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。