C++/代码:
class Solution { public: vector<int> PrintFromTopToBottom(TreeNode* root) { vector<int> res; //定一个一维数组,存放各个结点 if(!root) return res; //如果为空树,则返回res; queue<TreeNode*> q; //定一个TreeNode*队列 q.push(root); //插入root根结点 while (q.size()) { auto t = q.front(); //将结点赋值给t q.pop(); //弹出结点 res.push_back(t->val); //将t值插入res尾部 if (t->left) q.push(t->left); //先进先出,如果有左结点,插入 if (t->right) q.push(t->right); //如果有右结点,插入 } return res; } };