问题描述:给出一棵二叉树,返回其节点值的层次遍历(逐层从左往右访问)
样例:
给一棵二叉树
{3,9,20,#,#,15,7}
:
3
/ \
9 20
/ \
15 7
返回他的分层遍历结果:
[
[3],
[9,20],
[15,7]
]
实现思路:
创建一个队列,首先将根节点入队,当队列不空时,执行以下操作:定义一个向量level来存放每一层节点的数值,同时定义size表示队列的长度,为了后面判断当前层是否已经操作完毕。队头元素的值存入向量level中,然后队头元素出队,同时它的左右孩子入队。当当前层操作完毕后,将向量level存放到向量v中。若队列不空,继续进行下一层的操作。
实现代码:
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
/**
* @param root: The root of binary tree.
* @return: Level order a list of lists of integer
*/
public:
vector<vector<int>> levelOrder(TreeNode *root) {
// write your code here
vector<vector<int>> v;
if(root==NULL) return v;
queue<TreeNode*> q;
q.push(root);
while(!q.empty())
{
vector<int> level;
int size=q.size();
for(int i=0;i<size;++i)
{
TreeNode* node=q.front();
q.pop();
level.push_back(node->val);
if(node->left)
q.push(node->left);
if(node->right)
q.push(node->right);
}
v.push_back(level);
}
return v;
}
};
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
/**
* @param root: The root of binary tree.
* @return: Level order a list of lists of integer
*/
public:
vector<vector<int>> levelOrder(TreeNode *root) {
// write your code here
vector<vector<int>> v;
if(root==NULL) return v;
queue<TreeNode*> q;
q.push(root);
while(!q.empty())
{
vector<int> level;
int size=q.size();
for(int i=0;i<size;++i)
{
TreeNode* node=q.front();
q.pop();
level.push_back(node->val);
if(node->left)
q.push(node->left);
if(node->right)
q.push(node->right);
}
v.push_back(level);
}
return v;
}
};
做题感想:
开始时不明白vector<vector<int>>是什么意思,经同学指点知道是返回一个以向量为元素的向量。