有一棵二叉树,请设计一个算法,按照层次打印这棵二叉树。
给定二叉树的根结点root,请返回打印结果,结果按照每一层一个数组进行储存,所有数组的顺序按照层数从上往下,且每一层的数组内元素按照从左往右排列。保证结点数小于等于500。
用队列实现queue
用到队列queue的
queue <TreeNode> Q;
Q.front()//队列最先进去的元素
Q.back()//队列最后进去的元素
Q.push(x)//x元素进入队列
Q.pop()//弹出队列最先进去的元素
//二维vector的bush_back();
//为什么要申明中间变量node,直接用temp.front()不行呢?
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class TreePrinter {
public:
vector<vector<int> > printTree(TreeNode* root) {
vector<vector<int> > rec;
if(root==NULL)
return rec;
queue <TreeNode*> temp;
//TreeNode *t=root;
temp.push(root);
TreeNode *last=root;
TreeNode *nlast=NULL;
TreeNode *node=NULL;
vector<int> rec1;
while(!temp.empty())
{
node=temp.front();
if(node->left)
{
temp.push(node->left);
nlast=temp.back();
}
if(node->right)
{
temp.push(node->right);
nlast=temp.back();
}
rec1.push_back(node->val);
if(node==last)
{
last=nlast;
rec.push_back(rec1);
rec1.clear();
}
temp.pop();
}
return rec;
// write code here
}
};
用双向队列deque
temp.push();
temp.pop_front();
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;
deque<TreeNode*> temp;
if(root==NULL) return res;
TreeNode *cur=root;
temp.push_back(cur); //将头结点插入队列中
while(!temp.empty()){
if(temp.front()->left!=NULL) temp.push_back(temp.front()->left); //对于遍历到的节点,将他的左右节点放入到队列末尾
if(temp.front()->right!=NULL) temp.push_back(temp.front()->right);
res.push_back(temp.front()->val); //打印改节点
temp.pop_front(); //弹出该节点
}
return res;
}
};