用队列实现,每一层的节点的个数就是que的元素的个数,没保存一个节点的值,同时将相应节点的左右子结点保存进去。
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
/**
*
* @param root TreeNode类
* @return int整型vector<vector<>>
*/
vector<vector<int> > levelOrder(TreeNode* root) {
// write code here
vector<vector<int>> result{};
queue<TreeNode*> que{};
if(root==nullptr) return result;
que.push(root);
while(!que.empty()){
int n=que.size();
vector<int> level{};
for(int i=0;i<n;++i){
auto cur=que.front();
que.pop();
level.push_back(cur->val);
if(cur->left) que.push(cur->left);
if(cur->right) que.push(cur->right);
}
result.push_back(level);
}
return result;
}
};