简体   繁体   中英

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. 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 /
2 1 Output: 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<<" ";
    }
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM