class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
stack<TreeNode*> treeLeftToRight;
stack<TreeNode*> treeRightToLeft;
vector<vector<int>> result;
vector<int> tempResult;
TreeNode *tempTree;
treeLeftToRight.push(root);
while(!treeLeftToRight.empty() || !treeRightToLeft.empty()){
tempResult.clear();
while(!treeLeftToRight.empty()){
tempTree = treeLeftToRight.top();
if(tempTree){
tempResult.push_back(tempTree->val);
treeRightToLeft.push(tempTree->left);
treeRightToLeft.push(tempTree->right);
}
treeLeftToRight.pop();
}
if(tempResult.size()>0)
result.push_back(tempResult);
tempResult.clear();
while(!treeRightToLeft.empty()){
tempTree = treeRightToLeft.top();
if(tempTree){
tempResult.push_back(tempTree->val);
treeLeftToRight.push(tempTree->right);
treeLeftToRight.push(tempTree->left);
}
treeRightToLeft.pop();
}
if(tempResult.size()>0)
result.push_back(tempResult);
}
return result;
}
};
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
stack<TreeNode*> treeLeftToRight;
stack<TreeNode*> treeRightToLeft;
vector<vector<int>> result;
vector<int> tempResult;
TreeNode *tempTree;
treeLeftToRight.push(root);
while(!treeLeftToRight.empty() || !treeRightToLeft.empty()){
tempResult.clear();
while(!treeLeftToRight.empty()){
tempTree = treeLeftToRight.top();
if(tempTree){
tempResult.push_back(tempTree->val);
treeRightToLeft.push(tempTree->left);
treeRightToLeft.push(tempTree->right);
}
treeLeftToRight.pop();
}
if(tempResult.size()>0)
result.push_back(tempResult);
tempResult.clear();
while(!treeRightToLeft.empty()){
tempTree = treeRightToLeft.top();
if(tempTree){
tempResult.push_back(tempTree->val);
treeLeftToRight.push(tempTree->right);
treeLeftToRight.push(tempTree->left);
}
treeRightToLeft.pop();
}
if(tempResult.size()>0)
result.push_back(tempResult);
}
return result;
}
};