原文地址:https://www.jianshu.com/p/949969ade894
时间限制:1秒 空间限制:32768K
题目描述
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
我的代码
/*
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;
if(root==nullptr)
return res;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
TreeNode* cur=q.front();q.pop();
res.push_back(cur->val);
if(cur->left)
q.push(cur->left);
if(cur->right)
q.push(cur->right);
}
return res;
}
};
运行时间:3ms
占用内存:624k