Binary Tree Zigzag Level Order Traversal
Given a binary tree, return thezigzag level ordertraversal 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{3,9,20,#,#,15,7}
,
3 / \ 9 20 / \ 15 7
return its zigzag level order traversal as:
[ [3], [20,9], [15,7] ]
confused what"{1,#,2,3}"
means?> read more on how binary tree is serialized on OJ.
使用什么容器可以任君选择。
关键是考查层与层之间的访问顺序是不一样的,需要做一点特殊处理。
总体来说3到4星难度。
class Solution {
public:
vector<vector<int> > zigzagLevelOrder(TreeNode *root)
{
vector<vector<int> > v;
if (!root) return v;
deque<TreeNode *> qt1;
deque<TreeNode *> qt2;
qt1.push_back(root);
vector<int> itmedia;
itmedia.push_back(root->val);
v.push_back(itmedia);
itmedia.clear();
while (!qt1.empty())
{
while (!qt1.empty())
{
TreeNode *t = qt1.back();
qt1.pop_back();
if (t->right)
{
qt2.push_back(t->right);
itmedia.push_back(t->right->val);
}
if (t->left)
{
qt2.push_back(t->left);
itmedia.push_back(t->left->val);
}
}
if (!itmedia.empty()) v.push_back(itmedia);
itmedia.clear();
while (!qt2.empty())
{
TreeNode *t = qt2.back();
qt2.pop_back();
if (t->left)
{
qt1.push_back(t->left);
itmedia.push_back(t->left->val);
}
if (t->right)
{
qt1.push_back(t->right);
itmedia.push_back(t->right->val);
}
}
if (!itmedia.empty()) v.push_back(itmedia);
itmedia.clear();
}
return v;
}
};
//2014-2-16 update
vector<vector<int> > zigzagLevelOrder(TreeNode *root)
{
vector<vector<int> > rs;
if (!root) return rs;
stack<TreeNode *> stk[2];
stk[0].push(root);
bool flag = false;
while (!stk[flag].empty())
{
rs.push_back(vector<int>());
while (!stk[flag].empty())
{
TreeNode * t = stk[flag].top();
stk[flag].pop();
rs.back().push_back(t->val);
if (flag)
{
if (t->right) stk[!flag].push(t->right);
if (t->left) stk[!flag].push(t->left);
}
else
{
if (t->left) stk[!flag].push(t->left);
if (t->right) stk[!flag].push(t->right);
}
}
flag = !flag;
}
return rs;
}