题目描述

从上往下打印出二叉树的每个节点,同层节点从左至右打印。

​https://www.nowcoder.com/practice/7fe2212963db4790b57431d9ed259701?tpId=13&tqId=11175&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking​

题解:

class Solution {
public:
vector<int> PrintFromTopToBottom(TreeNode* root) {
if (root == NULL) {
return {};
}
queue<TreeNode*> q;
q.push(root);
vector<int> res;
while (q.empty() == false) {
TreeNode *t = q.front();
q.pop();
res.push_back(t->val);
if (t->left != NULL) {
q.push(t->left);
}
if (t->right != NULL) {
q.push(t->right);
}
}
return res;
}
};