Binary Tree Level Order Traversal
Given a binary tree, return thelevel ordertraversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree{3,9,20,#,#,15,7}
,
3 / \ 9 20 / \ 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]
confused what"{1,#,2,3}"
means?> read more on how binary tree is serialized on OJ.
利用两个队列会思路更加清晰点,增加了点额外空间。
class Solution {
public:
vector<vector<int> > levelOrder(TreeNode *root)
{
vector<vector<int> > v;
if (!root) return v;
queue<TreeNode *> qt1;
qt1.push(root);
queue<TreeNode *> qt2;
vector<int> itmedia;
itmedia.push_back(root->val);
v.push_back(itmedia);
itmedia.clear();
while (!qt1.empty())
{
while (!qt1.empty())
{
TreeNode *tn = qt1.front();
qt1.pop();
if (tn->left)
{
qt2.push(tn->left);
itmedia.push_back(tn->left->val);
}
if (tn->right)
{
qt2.push(tn->right);
itmedia.push_back(tn->right->val);
}
}
if (!qt2.empty())
{
qt1.swap(qt2);
v.push_back(itmedia);
itmedia.clear();
}
}
return v;
}
};
另外一种解法:
class Solution {
public:
vector<vector<int> > levelOrder(TreeNode *root)
{
vector<vector<int> > v;
if (!root) return v;
queue<TreeNode *> qt1;
qt1.push(root);
queue<TreeNode *> qt2;
vector<int> itmedia;
while (!qt1.empty())
{
while (!qt1.empty())
{
TreeNode *t = qt1.front();
qt1.pop();
itmedia.push_back(t->val);
if (t->left) qt2.push(t->left);
if (t->right) qt2.push(t->right);
}
v.push_back(itmedia);
itmedia.clear();
qt2.swap(qt1);
}
return v;
}
};
//2014-2-16 update
vector<vector<int> > levelOrder(TreeNode *root)
{
vector<vector<int> > rs;
if (!root) return rs;
queue<TreeNode *> qt[2];
qt[0].push(root);
bool flag = false;
while (!qt[flag].empty())
{
rs.push_back(vector<int>());
while (!qt[flag].empty())
{
TreeNode *t = qt[flag].front();
qt[flag].pop();
rs.back().push_back(t->val);
if (t->left) qt[!flag].push(t->left);
if (t->right) qt[!flag].push(t->right);
}
flag = !flag;
}
return rs;
}