题目
从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。
限制
节点总数 <= 1000
思路
使用队列来做,dfs,每次看一行
代码
/**
* 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) {
vector<vector<int>> res;
if (!root) return res;
queue<TreeNode *> q;
q.push(root);
while (q.size()) {
int len = q.size();
vector<int> level;
while (len -- ) {
auto t = q.front();
q.pop();
level.push_back(t -> val);
if (t -> left) q.push(t -> left);
if (t -> right) q.push(t -> right);
}
res.push_back(level);
}
return res;
}
};