问题描述
二叉树的螺旋/锯齿级顺序遍历。初始化指针向量以从前面遍历和弹出,但不知道为什么它不起作用
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());
}