题目描述
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
题目思路:
创建一个temp队列,将根节点放入到temp队列中,从队列中取元素,放入到res队列中,当取元素时判断取的元素有没有子节点,如果有子节点,则将子节点加入到temp队列中.
python:
class Solution:
def PrintFromTopToBottom(self, root):
if root is None:
return []
res = []
temp = [root]
while temp:
res.append(temp[0].val)
if temp[0].left:
temp.append(temp[0].left)
if temp[0].right:
temp.append(temp[0].right)
temp.pop(0)
return res
c++:
#include<vector>
#include<stdio.h>
#include<queue>
using namespace std;
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==NULL){
return res;
}
queue<TreeNode*> temp;
temp.push(root);
while(!temp.empty()){
res.push_back(temp.front()->val);
if(temp.front()->left){
temp.push(temp.front()->left);
}
if(temp.front()->right){
temp.push(temp.front()->right);
}
temp.pop();
}
return res;
}
};