[英]Vector of pointers throws error on push_back
二叉樹的螺旋/Zigzag級順序遍歷。 初始化指針向量以從前面遍歷和彈出,但不知道為什么它不起作用
這是我的代碼示例代碼:
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, _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 '->' ?)
v.push_back(v.begin()->left);
^~~~
D:\c++\trees\binaryTree.cpp:140:32: error: request for member 'right' 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()->right != NULL)
^~~~~
D:\c++\trees\binaryTree.cpp:142:45: error: request for member 'right' 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 '->' ?)
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());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.