代码随想录:二叉树的层序遍历
本来想用java写,但是太多代码细节不知道了,还是算了
/*** 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>> res;if (!root) return res;queue<TreeNode*> que;que.push(root);while (!que.empty()) {vector<int> temp;int size = que.size();while (size > 0) {TreeNode* target = que.front();que.pop();temp.push_back(target->val);if(target->left)que.push(target->left);if(target->right)que.push(target->right);size--;}res.push_back(temp);}return res;}
};