从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[9,20],
[15,7]
]
思路:
BFS:
但是和模板不同的地方在于 需要把 每一层 等分开
分开的方法就是在 从队列里面取出 结点之前,
先求出 这一层有几个结点.
注意:
处理一下空树的情况
代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> res;
queue<TreeNode*> q;
if(root == NULL) return res; //需要处理 空树的 情况吗?
q.push(root);
while(!q.empty())
{
vector<int> level;
int len = q.size();
for(int i = 0; i < len; i++)
{
TreeNode* temp_Node = q.front();
q.pop();
level.push_back(temp_Node->val);
if(temp_Node->left) q.push(temp_Node->left);
if(temp_Node->right) q.push(temp_Node->right);
}
res.push_back(level);
}
return res;
}
vector<vector<int>> ans;
};
vector::push_back()
只能向末尾添加元素
vector::insert()
(1) 某坐标前增加一个元素(迭代器)
vector <string> vec(2);
vec[0] = "123";vec[1] = "789";
vec.insert(vec.begin()+1,"456");
(2) 某坐标前增加n个相同的元素(迭代器)
vector <string> vec(2);
vec[0] = "123";vec[1] = "789";
vec.insert(vec.begin()+1,3,"456");