题解 | #从上往下打印二叉树#
从上往下打印二叉树
https://www.nowcoder.com/practice/7fe2212963db4790b57431d9ed259701
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
#include <cstddef>
#include <queue>
#include <vector>
class Solution {
public:
vector<int> PrintFromTopToBottom(TreeNode* root) {
vector<int> out;
if (!root) {
return out;
}
queue<TreeNode*> q;\
q.push(root);
while (!q.empty()) {
TreeNode* cur = q.front();
q.pop();
out.push_back(cur->val);
if (cur->left) {
q.push(cur->left);
}
if (cur->right) {
q.push(cur->right);
}
}
return out;
}
};
使用队列queue实现二叉树的层次遍历


华为技术有限公司工作强度 1291人发布