题解 | #从上往下打印二叉树#
从上往下打印二叉树
https://www.nowcoder.com/practice/7fe2212963db4790b57431d9ed259701?tpId=265&tqId=39234&rp=1&ru=/exam/oj/ta&qru=/exam/oj/ta&sourceUrl=%2Fexam%2Foj%2Fta%3FjudgeStatus%3D3%26page%3D1%26pageSize%3D50%26search%3D%26tpId%3D13%26type%3D265&difficulty=undefined&judgeStatus=3&tags=&title=
层次遍历
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
vector<int> PrintFromTopToBottom(TreeNode* root) {
std::vector<int> res;
if (root == nullptr) {
return res;
}
std::queue<TreeNode *> tree;
tree.push(root);
while (!tree.empty()) {
int size = tree.size();
for (int i = 0; i < size; ++i) {
TreeNode *tmp = tree.front();
tree.pop();
res.push_back(tmp->val);
if (tmp->left) {
tree.push(tmp->left);
}
if (tmp->right) {
tree.push(tmp->right);
}
}
}
return res;
}
};