[英]ZigZag Tree Traversal
Given a Binary Tree.给定一个二叉树。 Find the Zig-Zag Level Order Traversal of the Binary Tree.
找到二叉树的锯齿形水平顺序遍历。 Your Task: You don't need to read input or print anything.
您的任务:您不需要读取输入或打印任何内容。 Your task is to complete the function zigZagTraversal() which takes the root node of the Binary Tree as its input and returns a list containing the node values as they appear in the Zig-Zag Level-Order Traversal of the Tree.
您的任务是完成函数 zigZagTraversal(),该函数将二叉树的根节点作为其输入,并返回一个包含节点值的列表,这些节点值出现在树的 Zig-Zag Level-Order Traversal 中。 For Example: For the below binary tree the zigzag order traversal will be 1 3 2 7 6 5 4. Binary Tree Example enter image description here Input: 3 /
例如:对于下面的二叉树,锯齿形顺序遍历将是 1 3 2 7 6 5 4. 二叉树示例在此处输入图像描述输入:3 /
2 1 Output: 3 1 2 2 1 输出:3 1 2
My Code is showing segmentation fault我的代码显示分段错误
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<<" ";
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.