在我的二叉树前序遍历代码中,分段错误的原因是什么?

In my code for preorder traversal of binary tree, what is the reason for segmentation fault?

我必须 return 一个 int 向量中的二叉树的元素。我写了下面的代码,但它给出了分段错误。这可能是什么原因?另外,我的代码使用的逻辑是否正确?

struct Node
{    int data;
     struct *Node left;
     struct *Node right;
}
Node(int x)
{
     data = x;
     left = right = NULL;
}

vector <int> preorder(Node* root)
{
    vector <int> ans;
    if(root == NULL)
    {   
        return  {};
    }
    
    
    ans.push_back(root->data);
    ans.insert(ans.end(), preorder(root->left).begin(),preorder(root->left).end());
    ans.insert(ans.end(), preorder(root->right).begin(),preorder(root->right).end());
        
    
    return ans;

}

您为每个 ans.insert 调用了两次 preorder。它们将 return 不同的向量,它们的 begin()end() 不匹配。因此使用它们来指定范围是无效的。

而不是这个:

ans.insert(ans.end(), preorder(root->left).begin(),preorder(root->left).end());
ans.insert(ans.end(), preorder(root->right).begin(),preorder(root->right).end());

应该是:

vector<int> left_res = preorder(root->left);
ans.insert(ans.end(), left_res.begin(),left_res.end());
vector<int> right_res = preorder(root->right);
ans.insert(ans.end(), right_res.begin(),right_res.end());