Spiral/Zigzag level order traversal of binary tree. 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());
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.