[英]Vector of pointers throws error on push_back
Spiral/Zigzag level order traversal of binary tree.二叉树的螺旋/Zigzag级顺序遍历。 Initailize vector of pointers to traverse and pop from the front but don't know why its not working初始化指针向量以从前面遍历和弹出,但不知道为什么它不起作用
Here is my code sample Code:这是我的代码示例代码:
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++;
}
}
}
Error:错误:
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);
Here's the fix这是修复
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());
}
Also with front还有前面
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.