思路:
/**
* 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;
bfs(root,1,res);
return res;
}
void bfs(TreeNode* root,int level,vector<vector<int>>& res){
if(root == NULL) return ;
vector<int> tmp;
if(level > res.size()) res.push_back(tmp);
res[level-1].push_back(root->val); //注意,这里level不能替换成res.size()-1,调试了好久。。。
bfs(root->left,level+1,res);
bfs(root->right,level+1,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) {
if(root == NULL) return {};
vector<vector<int>> res;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
int size = q.size();
vector<int> level;
for(int i = 0; i < size; i++){
TreeNode *tmp = q.front();
level.push_back(tmp->val);
q.pop();
if(tmp->left) q.push(tmp->left);
if(tmp->right) q.push(tmp->right);
}
res.push_back(level);
}
return res;
}
};