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] ]BFS,宽度查找法。把同一级别的宽度记下来。訪问的同一时候把下一层弄到队列里面去。经常使用遍历方法!
class Solution { public: vector<vector<int>> zigzagLevelOrder(TreeNode* root) { vector<vector<int>> levelOrderStore; if (root==NULL) return levelOrderStore; queue<TreeNode *>q; stack<TreeNode *>rightout; q.push(root); rightout.push(root); int count=1; int level=0; vector<int> tmp(0); int flag=0;//begin right->left->right while (!q.empty())//q.root { tmp.clear(); level=0; for (int i=0;i<count;i++)//level { root=q.front(); //every root. q.pop(); if (flag%2==0) { tmp.push_back(root->val); } else { tmp.push_back(rightout.top()->val); //every root. rightout.pop();// } if (root->left!=NULL) { q.push(root->left); if (flag%2==0) { rightout.push(root->left); // } ++level; } if (root->right!=NULL) { q.push(root->right); if (flag%2==0) rightout.push(root->right); ++level; } } count=level; levelOrderStore.push_back(tmp); flag++; } return levelOrderStore; } };