32.从上到下打印二叉树
题目描述
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
分析
层序遍历二叉树,借助 队列 辅助。。
代码
/*
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) {
if (root == NULL) return {};
queue<TreeNode*> q;
TreeNode* read = root;
q.push(read);
vector<int> ret;
while (!q.empty()) {
TreeNode* tmp = q.front();
q.pop();
ret.push_back(tmp->val);
if (tmp->left) {
q.push(tmp->left);
}
if (tmp->right) {
q.push(tmp->right);
}
}
return ret;
}
};