问题描述
给出一棵树的前序和有序遍历,构造二叉树。 例如: 预购= [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上的堆缓冲区溢出
请帮助我。预先感谢。
解决方法
二进制搜索仅适用于已排序的对象,似乎没有对有序向量进行排序。