题目:从上往下打印出二叉树的每个节点,同层节点从左至右打印。
/*
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> vect;
if(root == NULL) return vect;
queue<TreeNode*> q;
q.push(root);
while(q.size()){ //如果队列里面还有值,则继续执行循环
TreeNode* cur_node = q.front();//q.front()返回的队头元素的引用
q.pop();
vect.push_back(cur_node->val);
if(cur_node->left) //关键步骤:队列中每有一个元素出队,就保存该元素的左右孩子(如果有)
q.push(cur_node->left);
if(cur_node->right)
q.push(cur_node->right);
}
return vect;
}
};