剑指 Offer 32 - II. 从上到下打印二叉树 II
思路:
使用队列来维护每一层,使用len记录每一层的个数,维护每一层就是计数len。
如果当前节点有左子树,则左子树入队列,如果当前节点有右子树,则右子树入队列。
代码:
/**
* 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) return {};
vector<vector<int>> res;
queue<TreeNode*> q;
q.push(root);
while(q.size()){
int len = q.size();
vector<int> path;
while(len--){
auto t = q.front();
q.pop();
path.push_back(t->val);
if(t->left) q.push(t->left);
if(t->right) q.push(t->right);
}
res.push_back(path);
}
return res;
}
};
评论区