题意
题解
方法一:广度优先搜索
/**
* 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>> ans;
if (!root) return ans;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
ans.push_back(vector<int>());
int n = q.size();
for (int i = 0; i < n; i++) {
TreeNode* head = q.front();
ans.back().push_back(head->val);
q.pop();
if (head->left) q.push(head->left);
if (head->right) q.push(head->right);
}
}
return ans;
}
};