版权声明:本文为原创博客,未经允许,请勿转载。 https://blog.csdn.net/u013095333/article/details/88599524
题目描述
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
链接
代码
/*
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> ans;
queue<TreeNode*> q;
if(root == NULL){
return ans;
}
else{
q.push(root);
}
while(!q.empty()){
TreeNode* temp = q.front();
ans.push_back(temp->val);
if(temp->left){
q.push(temp->left);
}
if(temp->right){
q.push(temp->right);
}
q.pop();
}
return ans;
}
};