[英]ZigZag Tree Traversal
給定一個二叉樹。 找到二叉樹的鋸齒形水平順序遍歷。 您的任務:您不需要讀取輸入或打印任何內容。 您的任務是完成函數 zigZagTraversal(),該函數將二叉樹的根節點作為其輸入,並返回一個包含節點值的列表,這些節點值出現在樹的 Zig-Zag Level-Order Traversal 中。 例如:對於下面的二叉樹,鋸齒形順序遍歷將是 1 3 2 7 6 5 4. 二叉樹示例在此處輸入圖像描述輸入: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<<" ";
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.