Created
August 31, 2014 07:42
-
-
Save xiren-wang/a1e1a7f6f2f703774e82 to your computer and use it in GitHub Desktop.
binary tree zigzag level order traversal.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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