题目一个难点是,用BFS做,怎么一层一层输出结果。如果是dfs,递归参数中加level即可,BFS可以在遍历队列的时候加一个for循环达到同样效果,看代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> ansArray;
vector<int> ans;
if (root == nullptr) return ansArray;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
ans.clear();
int qsize = q.size();
for(int i = 0; i<qsize; i++){
TreeNode* now = q.front();
q.pop();
ans.push_back(now->val);
if (now->left != nullptr) q.push(now->left);
if (now->right != nullptr) q.push(now->right);
}
ansArray.push_back(ans);
}
return ansArray;
}
};