title: 2019-8-19 分层打印二叉树
tags: 算法,每日一题,二叉树
分层打印二叉树
1. 题目描述
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
2. 题目解析
这题比较简单,就是将二叉树从根节点开始依次从上到下、从左到右打印二叉树的每一层。
2.1 思路解析
这道题关键是要想到要使用队列结构。依次将树的根节点以及其左孩子右孩子入队列中,再依次弹出再将弹出的节点的左孩子右孩子入队列,重复上面的过程直到队列为空即可。
/*
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) {
vector<int> res;
queue<TreeNode*> help_queue;
if (root != NULL) help_queue.push(root);
while(!help_queue.empty()){
root = help_queue.front(); help_queue.pop();
res.push_back(root->val);
if(root->left != NULL) help_queue.push(root->left);
if(root->right != NULL) help_queue.push(root->right);
}
return res;
}
};
更多关于编程和机器学习资料请关注FlyAI公众号。