《剑指offer》从上往下打印二叉树
一、题目描述
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
二、输入描述
一棵树
三、输出描述
输出层次遍历顺序
四、牛客网提供的框架
/*
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) {
}
};
五、解题思路
这是树的层次遍历。使用一个队列,先头结点队。出队列,对出队元素的左右节点分别入队。循环,直到队列为空。
六、代码
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
queue<TreeNode *> pushNodeQueue;
vector<int> PrintFromTopToBottom(TreeNode *root) {
vector<int> result;
if(root) pushNodeQueue.push(root);
while(!pushNodeQueue.empty())
{
TreeNode* f = pushNodeQueue.front();
pushNodeQueue.pop();
result.push_back(f->val);
if(f->left) pushNodeQueue.push(f->left);
if(f->right) pushNodeQueue.push(f->right);
}
return result;
}
};