原题:
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
这个题其实就是二叉树的层次遍历,跟前边的这个题基本类似Populating Next Right Pointers in Each Node
基本思想都是在每一层的最后加一个NULL,用来分辨各层,需要注意:
1 对vector的使用,每一层都要新建一个vector<int>,用来保存新一层的数据,注意要用地址传。。。
2 每遇到一个NULL,则把上一个vector入result,并新建vector用来保存下一层的数据
3 对NULL要多一个判断,看是否是最后一个NULL,防止进入无限循环。
代码(24ms):
class Solution {
public:
vector<vector<int> > levelOrder(TreeNode *root) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
vector<vector<int>>result;
if(!root) return result;
queue <TreeNode*>q;
q.push(root);
q.push(NULL);
vector<int>current;
vector<int>&temp = current;
while(!q.empty()){
TreeNode * front = q.front();
q.pop();
if(front){
//头部不为空,把头部的值压入vector
//若该头部左右不为空,则入队列
temp.push_back(front->val);
if(front->left) q.push(front->left);
if(front->right) q.push(front->right);
}
else{
//头部为空,把上一次的vector整体压入result
result.push_back(temp);
//若为空,说明在处理最后一个NULL,不用push等操作
if(!q.empty()){
q.push(NULL);
vector<int>current;
//新建的vector,用以保存下一层的数据
temp = current;
}
}
}
return result;
}
};