题解 | #从上往下打印二叉树#
从上往下打印二叉树
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 <queue>
#include <vector>
class Solution {
public:
vector<int> PrintFromTopToBottom(TreeNode* root) {
vector<int > tree;
queue<TreeNode *> qu;
if (root == nullptr) {
return tree;
}
qu.push(root);
while (!qu.empty()) {
TreeNode *node = qu.front();
qu.pop(); //出队
tree.push_back(node->val);
if (node->left) qu.push(node->left);
if (node->right) qu.push(node->right);
}
return tree;
}
};
查看28道真题和解析