思路不同于y总的地方
y总视频思路为
在每一层添加一个nullptr元素用于标识一层变量的结束符。
本文思路
计算每一层的元素的size大小,然后for循环size次,一个for循环对应一个level、对应一次res.push_back(level)。
代码
/**
* 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>> printFromTopToBottom(TreeNode* root) {
vector<vector<int>> res;
if (root == NULL) return res;
queue<TreeNode*> q;
q.push(root);
vector<int> level;
while (q.size()) {
level.clear();
int size = q.size(); // 每一层的节点数量,size为下一行的循环次数,即level有多少个元素
for (int i = 0; i < size; i ++ ) {
auto t = q.front();
q.pop();
level.push_back(t->val); // size多大,level多长
if (t->left) q.push(t->left); // 这两行将q扩充,用于计算下一次while循环的size值
if (t->right) q.push(t->right);
}
res.push_back(level); // for循环结束,也就是遍历完一层
}
return res;
}
};
参考
1.Algocasts网站:https://algocasts.io/episodes/qjG0bWK2
2.LeetCode专栏: https://leetcode-cn.com/leetbook/read/illustration-of-algorithm/5v22om/
记录,共同成长~