链接:https://leetcode.cn/problems/cong-shang-dao-xia-da-yin-er-cha-shu-lcof
题目描述:从上到下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印。
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回:
[3,9,20,15,7]
代码:
class Solution {
public:
vector<int> levelOrder(TreeNode* root) {
vector<int> res;
if(!root) return res;
queue<TreeNode* > q;
q.push(root);
while(q.size()) {
TreeNode* node = q.front();
q.pop();
res.push_back(node -> val);
if(node -> left) q.push(node -> left);
if(node -> right) q.push(node -> right);
}
return res;
}
};