Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xiren-wang/a1e1a7f6f2f703774e82 to your computer and use it in GitHub Desktop.
Save xiren-wang/a1e1a7f6f2f703774e82 to your computer and use it in GitHub Desktop.
binary tree zigzag level order traversal.
/**
* 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) {
//push BFS to two queues; once current queue empty, switch
// note to reverse the vector every other level
vector<vector<int> > vvInt;
queue<TreeNode *> parentQ;
if (root)
parentQ.push(root);
queue<TreeNode *> childrenQ;
bool forwardDirection = true;
vector<int> vInt;
while ( !parentQ.empty() ) {
TreeNode * aNode = parentQ.front();
parentQ.pop();
vInt.push_back(aNode->val);
if (aNode->left)
childrenQ.push(aNode->left);
if (aNode->right)
childrenQ.push(aNode->right);
if (parentQ.empty()) {
//one level is done
//switch to next level
swap(parentQ, childrenQ);
if (!forwardDirection) //reverse vInt
reverse(vInt.begin(), vInt.end());
vvInt.push_back(vInt);
vInt.clear();
forwardDirection = !forwardDirection;
}
}
return vvInt;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment