题目描述
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
思路:非递归,层次遍历,即广度优先算法(bfs),使用队列
1、将根节点入队;
2、若队列非空,取队首元素,push到vector中;
3、将下一层节点加入到队尾
4、重复2、3,直到队列为空
/*
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;
//思路1:层次遍历,非递归,用队列
queue<TreeNode*> q;
q.push(root);
while (!q.empty())
{
TreeNode* tmp = q.front();
q.pop();
res.push_back(tmp->val);
if (tmp->left)
q.push(tmp->left);
if (tmp->right)
q.push(tmp->right);
}
return res;
}
};