Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the
next level and alternate between).
For example:
Given binary tree {3,9,20,#,#,15,7}
,
3 / \ 9 20 / \ 15 7
return its zigzag level order traversal as:
[ [3], [20,9], [15,7] ]
/** * 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) { // Start typing your C/C++ solution below // DO NOT write int main() function vector<vector<int>> result; if(!root) return result; vector<int> tmp; queue<TreeNode*> q1, q2; q1.push(root); TreeNode *cur; int order = 1; while(!q1.empty()){ tmp.clear(); while(!q1.empty()){ cur = q1.front(); q1.pop(); tmp.push_back(cur->val); if(cur -> left) q2.push(cur->left); if(cur -> right) q2.push(cur->right); } if(order == 1){ result.push_back(tmp); order = 0; }else{ reverse(tmp.begin(), tmp.end()); result.push_back(tmp); order = 1; } swap(q1, q2); } return result; } };