我必须从预订和顺序遍历构建一个树。代码在我的笔记本电脑上工作正常,但不在leetcode上。它给出了运行时错误,有什么建议吗?
int findindex(vector<int>& inorder,int index) {
int size = inorder.size();
for(int i=0;i<size;i++)
{
if(index == inorder[i])
return index;
} }
TreeNode* helper(vector<int>& preorder, vector<int>& inorder, int start, int end) {
static int preindex = 0;
if(start > end)
return NULL;
TreeNode* head;
head = (TreeNode *)malloc(sizeof(TreeNode));
head->val = preorder[preindex++];
head->left = NULL;
head->right = NULL;
if(start == end)
return head;
int index = findindex(inorder,head->val);
head->left = helper(preorder, inorder,start, index-1);
head ->right = helper(preorder, inorder, index+1, end);
return head; }
TreeNode* Solution::buildTree(vector<int> &preorder, vector<int> &inorder) {
int size = preorder.size();
if(size == 0)
return NULL;
return helper(preorder, inorder, 0, size-1); }