给出一棵二叉树,返回其节点值的层次遍历(逐层从左往右访问)
样例
样例 1:
输入:{1,2,3}
输出:[[1],[2,3]]
解释:
1
/ \
2 3
它将被序列化为{1,2,3}
层次遍历
样例 2:
输入:{1,#,2,3}
输出:[[1],[2],[3]]
解释:
1
\
2
/
3
它将被序列化为{1,#,2,3}
层次遍历
挑战
挑战1:只使用一个队列去实现它
挑战2:用BFS算法来做
注意事项
首个数据为根节点,后面接着是其左儿子和右儿子节点值,"#"表示不存在该子节点。
节点数量不超过20。
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {//queue
public:
/**
* @param root: A Tree
* @return: Level order a list of lists of integer
*/
vector<vector<int>> levelOrder(TreeNode * root) {
// write your code here
vector<vector<int>>res;
if(root==NULL) return res;
vector<int> tmp;
queue<TreeNode *>que;
que.push(root);
while(que.size())
{
int i=que.size();
int j=0;
while(j<i)
{
TreeNode*node=que.front();
tmp.push_back(node->val);
que.pop();
j++;
if(node->left)que.push(node->left);
if(node->right)que.push(node->right);
}
res.push_back(tmp);
tmp.clear();
}
return res;
}
};
//BFS
vector<vector<int>> levelOrder(TreeNode *root)
{
vector<vector<int>> result;
traverse(root, 0, result);
return result;
}
void traverse(TreeNode *root, size_t level, vector<vector<int>> &result)
{
if(root == NULL)
{
return;
}
if(result.size() == level)
{
result.push_back(vector<int>());
}
result[level].push_back(root->val);
if(root->left != NULL)
{
traverse(root->left, level+1, result);
}
if(root->right != NULL)
{
traverse(root->right, level+1, result);
}
}