问题描述
给出一个二叉树。查找二叉树的之字形水平阶遍历。
你的任务:
您无需阅读输入或打印任何内容。您的任务是完成函数zigzagTraversal(),该函数将二叉树的根节点作为其输入,并返回一个包含节点值的列表,这些节点值出现在树的Zig-Zag Level-Order遍历中。
例如:对于下面的二叉树,之字形顺序遍历为1 3 2 7 6 5 4.二叉树示例enter image description here
输入:
3
/
2 1
输出:3 1 2
enter code here
vector <int> zigzagTraversal(Node* root)
{
// Code here
if(root==0)
{
return {0};
}
stack<Node *> s1;
stack<Node *> s2;
vector<int> m;
m.push_back(root->data);
s1.push(root->left);
s1.push(root->right);
while(s1.empty()==false || s2.empty()==false)
{
if(s1.empty()==false)
{
while(s1.empty()==false)
{Node *f=s1.top();
if(s1.top()->right!=0)
{
s2.push(f->right);
}
if(s1.top()->left!=0)
{
s2.push(f->left);
}
m.push_back(f->data);
s1.pop();
}
}
else if(s2.empty()==false)
{
while(s2.empty()==false)
{
if(s2.top()->left!=0)
{Node *f=s2.top();
s1.push(f->left);
}
if(s2.top()->right!=0)
{Node *f=s2.top();
s1.push(f->right);
}
Node *f=s2.top();
m.push_back(f->data);
s2.pop();
}
}
}
return m;
}
解决方法
//hope this helps u
void zigZagTraversal(Node *root)
{
int h=0;
queue<pair<Node*,int>> q;
Node *t;
map<int,vector<int>> m;
vector<int> v;
q.push({root,h});
while(!q.empty()){
t=q.front().first;
h=q.front().second;
q.pop();
if(t){
m[h].push_back(t->data);
q.push({t->left,h+1});
q.push({t->right,h+1});
}
}
for(auto i=m.begin();i!=m.end();i++){
v=m[i->first];
if(!((i->first)%2)){
reverse(v.begin(),v.end());
}
for(auto j=v.begin();j!=v.end();j++) cout<<*j<<" ";
}
}