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] ]
分析:这道与level order traversal不同的地方在于相邻层元素的访问方向是相反的,我们可以用一个bool变量来标记访问的方向,代码如下:
1 class Solution { 2 public: 3 vector<vector<int> > zigzagLevelOrder(TreeNode *root) { 4 vector<vector<int> > result; 5 if(root == NULL) return result; 6 7 bool direction = false;//false indicates from left to right 8 vector<TreeNode *> prev(1, root); 9 10 while(!prev.empty()){ 11 vector<int> level; 12 vector<TreeNode *> cur; 13 for(auto i = prev.begin(); i != prev.end(); i++){ 14 level.push_back((*i)->val); 15 if((*i)->left) cur.push_back((*i)->left); 16 if((*i)->right) cur.push_back((*i)->right); 17 } 18 if(direction) 19 reverse(level.begin(), level.end()); 20 result.push_back(level); 21 prev = cur; 22 direction ^= true; 23 } 24 25 return result; 26 } 27 };