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.
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> >ret; vector<int> inner; bool direction=false; TreeNode **array=new TreeNode*[10000]; if(!root) return ret; array[0]=root; inner.push_back(root->val); ret.push_back(inner); int p=0,flag=1,q=1; for( ; p!=q ; p++ ){ if(p==flag){ flag=q; inner.clear(); if(!direction){ for(int i=q-1 ; i>=p ; i--) inner.push_back(array[i]->val); } else{ for(int i=p ; i<q ; i++) inner.push_back(array[i]->val); } direction=!direction; ret.push_back(inner); } if(array[p]->left) array[q++]=array[p]->left; if(array[p]->right) array[q++]=array[p]->right; } return ret; } };