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

指针向量在 push_back 上引发错误

如何解决指针向量在 push_back 上引发错误

二叉树的螺旋/锯齿级顺序遍历。初始化指针向量以从前面遍历和弹出,但不知道为什么它不起作用

Spiral tree print

这是我的代码示例 代码

void spiralPrint(Node *root)
        {
            if(root!=NULL)
            {
                vector<Node *> v;
                v.push_back(root);
                int j=1;
                while(v.empty() == false)
                {
                    int count = v.size();
                    for(int i=0; i<count; i++)
                    {
                        if(*v.begin()->left != NULL)
                        {
                            v.push_back(*v.begin()->left);
                        }
                        if(*v.begin()->right != NULL)
                        {
                            v.push_back(*v.begin()->right);
                        }
                        v.erase(v.begin());
                    }
                    j++;
                }
            }
        }

错误

D:\c++\trees\binaryTree.cpp: In function 'void spiralPrint(Node)': 
D:\c++\trees\binaryTree.cpp:136:32: error: request for member 'left' in ' v.std::vector<_Tp,_Alloc>::begin<Node,std::allocator<Node> >().gnu_cxx::normal_iterator<_Iterator,_Container>::operator-><Node,std::vector<Node> >()',which is of pointer type 'Node' (maybe you meant to use '->' ?) 
        if(v.begin()->left != NULL) 
        ^~~~ 
        D:\c++\trees\binaryTree.cpp:138:45: error: request for member 'left' in ' v.std::vector<_Tp,which is of pointer type 'Node' (maybe you meant to use '->' ?)
        v.push_back(v.begin()->left); 
        ^~~~ 
        D:\c++\trees\binaryTree.cpp:140:32: error: request for member 'right' in ' v.std::vector<_Tp,which is of pointer type 'Node' (maybe you meant to use '->' ?) 
        if(v.begin()->right != NULL) 
        ^~~~~ 
        D:\c++\trees\binaryTree.cpp:142:45: error: request for member 'right' in ' v.std::vector<_Tp,which is of pointer type 'Node' (maybe you meant to use '->' ?)
        v.push_back(*v.begin()->right); 

解决方法

解决办法

for(int i=0; i<count; i++)
   {
      auto it = *v.begin();
      if(it->left != NULL)
      {
          v.push_back(it->left);
      }
      if(it->right != NULL)
      {
          v.push_back(it->right);
      }
      v.erase(v.begin());
   }

也有正面

for(int i=0; i<count; i++)
   {
       if(v.front()->left != NULL)
       {
          v.push_back(v.front()->left);
       }
       if(v.front()->right != NULL)
       {
          v.push_back(v.front()->right);
       }
       v.erase(v.begin());
   }

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