一:题目描述
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
二:解题思路
借助队列实现
在之前的一道剑指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) {
vector<int> result;
if(root==NULL)
return result;
queue<TreeNode*> pNode;
pNode.push(root);
while(!pNode.empty()){
//队列不为空
//队首出队
TreeNode* temp=pNode.front();
//保存该结点的值
result.push_back(temp->val);
//该结点出队
pNode.pop();
if(temp->left!=NULL)
pNode.push(temp->left);
if(temp->right!=NULL)
pNode.push(temp->right);
}
return result;
}
};