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
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] ]
confused what
Analysis:
"{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
class Solution {
public:
vector<vector<int> > zigzagLevelOrder(TreeNode *root) {
vector<vector<int> > ret;
if (root == NULL)
return ret;
queue<TreeNode*> q;
int currLevel = 1;
int nextLevel = 0;
q.push(root);
vector<int> row;
int level = 1;
while(!q.empty())
{
TreeNode* t = q.front();
q.pop();
currLevel--;
if (level % 2 == 1)
row.push_back(t->val);
else
row.insert(row.begin(), t->val);
if (t->left != NULL)
{
q.push(t->left);
nextLevel++;
}
if (t->right != NULL)
{
q.push(t->right);
nextLevel++;
}
if (currLevel == 0)
{
level++;
currLevel = nextLevel;
nextLevel = 0;
ret.push_back(row);
row.clear();
}
}
return ret;
}
};
No comments:
Post a Comment