题目描述
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
思路
从上往下,从左往右,就是层排序。
按照层排序,打印顺序是 1 2 3 4 5 6 7 8 9
这道题的关键思想,就是用一个队列来保存各结点。
假设,二叉树不为空,那么根结点(root)必定第一个打印,将该结点插入队列。现在队列queue = 【1】。
(1)如果队列不为空,打印队列首位置的结点值;
(2)判断该结点的左子结点是否为空,不为空,插入队列;再判断又子结点是否为空,不为空,插入队列;
(3)将队首结点弹出,继续(1)
代码
/*
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()){
int size = q.size();
for (int i = 0; i < size; ++i){
auto cur = q.front();
res.emplace_back(cur->val);
q.pop();
if (cur->left) q.push(cur->left);
if (cur->right) q.push(cur->right);
}
}
return res;
}
};