算法题目 :Binary Tree Level Order Traversal
算法题目描述:
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]
算法分析:
这道题目还是二叉树的层序遍历,利用两个队列,从根节点开始,放到第一个队列中,下一层次的节点放到另一个队列中。
算法代码(C++):
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode*&root) {
queue<TreeNode*>q1;
vector<vector<int>>ovec;
vector<int>ivec;
TreeNode *temp = root;
if(!temp)
return ovec;
q1.push(temp);
do
{
queue<TreeNode*>q2;;
while (!q1.empty())
{
temp = q1.front();
ivec.push_back(temp->val);
q1.pop();
if (temp->left)
q2.push(temp->left);
if (temp->right)
q2.push(temp->right);
}
ovec.push_back(ivec);
ivec.clear();
q1 = q2;
} while (!q1.empty());
return ovec;
}
};
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode*&root) {
queue<TreeNode*>q1;
vector<vector<int>>ovec;
vector<int>ivec;
TreeNode *temp = root;
if(!temp)
return ovec;
q1.push(temp);
do
{
queue<TreeNode*>q2;;
while (!q1.empty())
{
temp = q1.front();
ivec.push_back(temp->val);
q1.pop();
if (temp->left)
q2.push(temp->left);
if (temp->right)
q2.push(temp->right);
}
ovec.push_back(ivec);
ivec.clear();
q1 = q2;
} while (!q1.empty());
return ovec;
}
};