题目地址:
https://www.acwing.com/problem/content/41/
从上往下打印出二叉树的每个结点,同一层的结点按照从左到右的顺序打印。
数据范围:
树中节点的数量
[
0
,
1000
]
[0,1000]
[0,1000]。
代码如下:
#include <vector>
#include <queue>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
vector<int> printFromTopToBottom(TreeNode* root) {
vector<int> res;
if (!root) return res;
queue<TreeNode*> q;
q.push(root);
while (q.size()) {
auto t = q.front(); q.pop();
res.push_back(t->val);
if (t->left) q.push(t->left);
if (t->right) q.push(t->right);
}
return res;
}
};
时空复杂度 O ( n ) O(n) O(n)。