[LeetCode]Binary Tree Zigzag Level Order Traversal
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] ]
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
OJ's Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
Here's an example:
1 / \ 2 3 / 4 \ 5
The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}"
.
思考:偶数层直接反转,竟然过了。
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { private: vector<vector<int> > ret; public: vector<vector<int> > zigzagLevelOrder(TreeNode *root) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. ret.clear(); if(root==NULL) return ret; vector<int> ans; queue<TreeNode *> q; q.push(root); int num=1; while(!q.empty()) { ans.clear(); int count=0; while(num--) { TreeNode *node=q.front(); q.pop(); ans.push_back(node->val); if(node->left) { count++; q.push(node->left); } if(node->right) { count++; q.push(node->right); } } num=count; ret.push_back(ans); } for(int i=0;i<ret.size();i++) { if(i%2==0) continue; for(int j=0;j<ret[i].size()/2;j++) swap(ret[i][j],ret[i][ret[i].size()-j-1]); } return ret; } };