C++ 我的代码中有一个错误。问题:从前序和序遍历构造二叉树
给定树的前序和无序遍历,构造二叉树。 例如: 前序=[3,9,20,15,7] 顺序=[9,3,15,20,7] 返回二叉树 我的代码如下:C++ 我的代码中有一个错误。问题:从前序和序遍历构造二叉树,c++,binary-tree,inorder,preorder,C++,Binary Tree,Inorder,Preorder,给定树的前序和无序遍历,构造二叉树。 例如: 前序=[3,9,20,15,7] 顺序=[9,3,15,20,7] 返回二叉树 我的代码如下: //helper function TreeNode* build(vector<int> &preorder, vector<int> &inorder, int start, int end) { static int index = 0; if(start>end) ret
//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
}
//helper函数
TreeNode*构建(向量和预序、向量和索引序、整数开始、整数结束)
{
静态int指数=0;
如果(开始>结束)
返回NULL;
TreeNode*root=新的TreeNode(预排序[index++]);//新节点创建
if(start==end)//如果没有剩下元素,则返回
返回根;
int preindex=binary_search(inoorder.begin(),inoorder.end(),root->val);//查找新迭代的根位置
root->left=build(预排序、顺序、开始、预索引-1);//对left进行递归
root->right=build(预排序、顺序、预索引+1、结束);//右循环
返回根;//返回根
}
TreeNode*构建树(向量和前序,向量和索引){
int start=0;
int end=preorder.size()-1;
返回构建(预排序、索引、开始、结束);//调用helper函数
}
上面的代码显示了一个错误
=错误:AddressSanitizer:pc 0x000000382d77 bp 0x7ffc26698900 sp 0x7ffc266988f8上的地址0x603000000030上的堆缓冲区溢出
请帮帮我,伙计们。提前感谢。二进制搜索仅适用于已排序的对象,并且似乎没有对索引向量进行排序