binary tree zigzag level order traversal leetcode c++

来源:互联网 发布:网页模板源码下载 编辑:程序博客网 时间:2024/05/22 00:09

we just use a flag parameter called layer and with the help of a stack to accomplish the function.It just like the level order traversal on binary tree.

/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * };*/class Solution {public:    vector<vector<int> > zigzagLevelOrder(TreeNode *root) {    vector<vector<int>> ans;    if(root == NULL)        return ans;    int count = 1;//count is the number of each layer//two     queue<TreeNode *> q;    q.push(root);    vector<int> cur(0);    int layer = 0;    while(!q.empty())    {        cur.clear();        stack<int> s;        int tmp = 0;        for(int i = 0;i< count;i++)        {            root = q.front();            if(layer%2 == 0)            {                cur.push_back(root->val);                q.pop();            }            if(layer%2 == 1)            {                s.push(root->val);                q.pop();            }            if(root->left!= NULL)            {                q.push(root->left);                tmp++;            }            if(root->right!= NULL)            {                q.push(root->right);                tmp++;            }                }        if(layer%2 == 1)        {            while(!s.empty())            {                cur.push_back(s.top());                s.pop();            }        }        layer ++;        count = tmp;        ans.push_back(cur);    }    return ans;    }};


0 0