【剑指offer】从上往下打印二叉树
题目描述
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
思路
利用队列实现二叉树的层次遍历,要注意一定要特判一下二叉树为空的情况,我就坑这了~
代码
/*
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> vec;
if(!root){
return vec;
}
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
TreeNode* t = q.front();
q.pop();
vec.push_back(t->val);
if(t->left){
q.push(t->left);
}
if(t->right){
q.push(t->right);
}
}
return vec;
}
};