给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[9,20],
[15,7]
]
层序遍历指按层次的顺序从根结点向下逐层进行遍历,且对同一层的节点为从左到右遍历。
基本思路:从根结点开始广度优先搜索
- 将根结点root加入队列
- 取出队首结点,访问它
- 如果该结点有左孩子,将左孩子入队。
- 如果该结点有右孩子,将右孩子入队
- 返回第二步,直到队列为空
/**
* 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;
if(root == NULL) {
return res;
}
queue<TreeNode*> q;
TreeNode* p;
q.push(root);
while(!q.empty()) {
vector<int> temp;
int width = q.size();
for(int i = 0; i < width; i++) {
p = q.front();
temp.push_back(p->val);
q.pop();
if(p->left) {
q.push(p->left);
}
if(p->right) {
q.push(p->right);
}
}
res.push_back(temp);
}
return res;
}
};
/**
* 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) {
queue<TreeNode*> q;
vector<vector<int>> res;
q.push(root);
if(root==NULL){
return res;
}
while(!q.empty()){
queue<TreeNode*> qt;
vector<int> v;
while(!q.empty()){
TreeNode* now = q.front();
q.pop();
v.push_back(now->val);
if(now->left!=NULL){
qt.push(now->left);
}
if(now->right!=NULL){
qt.push(now->right);
}
}
res.push_back(v);
q = qt;
}
return res;
}
};