Binary Tree Zigzag Level Order Traversal
yinlinglin opened this issue · comments
class Solution {
public:
vector<vector > zigzagLevelOrder(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<vector> result;
if(root==NULL) return result;
vector<TreeNode * >v;
v.push_back(root);
bool leftsonfirst = true;
int index,begin = 0;
while(1)
{
vector newv;
newv.clear();
index = v.size();
if(index == begin) break;
int p = index-1;
while(p>=begin)
{
if(v[p]!=NULL)
{
newv.push_back(v[p]->val);
if(leftsonfirst)
{
v.push_back(v[p]->left);
v.push_back(v[p]->right);
}
else
{
v.push_back(v[p]->right);
v.push_back(v[p]->left);
}
}
p--;
}
if(newv.size())
result.push_back(newv);
begin = index;
leftsonfirst = !leftsonfirst;
}
return result;
}
};