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

为什么它给我段错误?二叉树的垂直视图

如何解决为什么它给我段错误?二叉树的垂直视图

给定的代码不被接受并给我段错误。我使用 map 来存储垂直线值以及每行上的树节点数据。

void getvorder(Node *root,map<int,vector<int>> &m,int hd)
 {
     
     //base case
     if(root==NULL)
     return;
     
     m[hd].push_back(root->data);
     
     getvorder(root,m,hd-1);
     getvorder(root,hd+1);
 }

// root:树的根节点

vector<int> verticalOrder(Node *root)
{
    //Your code here
    vector<int> v;
    map<int,vector<int>>m;
    //initial hd=0;
    int hd=0;
    if(root==NULL) return v;
    getvorder(root,hd);
    //traverse the map and print each element
    map<int,vector<int>> :: iterator it;
    for(it=m.begin();it!=m.end();it++)
    {
        for(int i=0;i<it->second.size();i++)
        {
            v.push_back(it->second[i]);
        }
    }
 return v;
    
    
}

解决方法

您收到以下错误:

AddressSanitizer:DEADLYSIGNAL
=================================================================
==31==ERROR: AddressSanitizer: stack-overflow on address 0x7ffc3eabcff8 (pc 0x0000002a08c3 bp 0x000000000040 sp 0x7ffc3eabd000 T0)
==31==ABORTING

通常递归中的 stack-overflow 错误表示递归陷入无限循环,这意味着递归调用永远不会满足基本情况。

现在,如果您在检查代码时牢记递归调用中存在问题,可能有助于轻松找到问题。您对 getvorder() 的递归调用是问题的根源,因为您使用 root 节点重复调用此函数,并且当此 root 节点变为 null(您的基本情况)。现在,当您使用同一个节点一次又一次地调用 getvorder() 函数时,它会产生 stack-overflow 错误。

以下代码解决问题:

void getvorder(Node *root,map<int,vector<int>> &m,int hd)
{
     //base case
     if(root==NULL) return;
     
     m[hd].push_back(root->data);
     
     getvorder(root->left,m,hd-1);
     getvorder(root->right,hd+1);
 }

// root: root node of the tree
vector<int> verticalOrder(Node *root)
{
    //Your code here
    vector<int> v;
    map<int,vector<int>>m;
    //initial hd=0;
    int hd=0;
    if(root==NULL) return v;
    getvorder(root,hd);
    //traverse the map and print each element
    map<int,vector<int>> :: iterator it;
    for(it=m.begin();it!=m.end();it++)
    {
        for(int i=0;i<it->second.size();i++)
        {
            v.push_back(it->second[i]);
        }
    }
    return v;
}

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