题目描述
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
解题思路:
又叫BFS或者二叉树层序遍历。
需要使用queue队列来保存每层的节点信息。(对于树操作,经常使用递归,但是这个题目使用递归会有违题意,需要破除思维定式)
class Solution {
public:
queue<TreeNode*>Que;
vector<int> PrintFromTopToBottom(TreeNode* root) {
if(root != NULL){
Que.push(root);
}
vector<int> res;
while(!Que.empty()){
TreeNode *elem = Que.front();
Que.pop();
res.push_back(elem->val);
if(elem->left != NULL){
Que.push(elem->left);
}
if(elem->right != NULL){
Que.push(elem->right);
}
}
return res;
}
};