1. 牛客网链接: 我是链接
2. 题目描述:
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
输入:二叉树根节点(可以为空)
二叉树节点结构:
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
输出:二叉树层序遍历(从左往右)
3. 题目分析:
该题为二叉树的层序遍历应用,即可使用队列保存二叉树的每一层然后按照压入队列的元素的顺序打印。
**4. 代码实现: **
class Solution {
public:
vector<int> result;
vector<int> PrintFromTopToBottom(TreeNode* root) {
if(root==NULL)return result;
queue<TreeNode*> print;//使用队列进行二叉树层序遍历
print.push(root);//将根压入队列中
while(!print.empty())//如果队列为空则停止循环
{
TreeNode* cur=print.front();//从队列头部取出节点打印
print.pop();
if(cur!=NULL){//如果当前节点不为空则打印入结果数据结构vector<int> result
result.push_back(cur->val);
print.push(cur->left);//当前节点的下一层即左右节点压入队列中
print.push(cur->right);
}
}
return result;
}
};