【题目描述】
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
【思路】
借助队列,完成二叉树的层序遍历。
【代码】
C++中队列的操作: 1.q.push():入队
2.q.pop():出队
3.q.front():取队头
4.q.empty():判空
5.q.back():取队尾
C++:
#include <queue>
class Solution {
public:
vector<int> PrintFromTopToBottom(TreeNode* root) {
vector<int> re;
if(root==NULL){
return re;
}
queue<TreeNode*> q;
q.push(root);
while(q.size()){
TreeNode* head=q.front();
q.pop();
re.push_back(head->val);
if(head->left){
q.push(head->left);
}
if(head->right){
q.push(head->right);
}
}
return re;
}
};
python:
class Solution:
# 返回从上到下每个节点值列表,例:[1,2,3]
def PrintFromTopToBottom(self, root):
# write code here
if not root:
return []
queue=[]
queue.append(root)
re=[]
while(queue):
head=queue.pop(0)
re.append(head.val)
if head.left:
queue.append(head.left)
if head.right:
queue.append(head.right)
return re