题目描述
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
BFS:
//层次遍历
class Solution {
public:
vector<vector<int> > Print(TreeNode* pRoot) {
vector<vector<int> > vec;
if(pRoot == NULL) return vec;
queue<TreeNode*> q;
q.push(pRoot);
while(!q.empty())
{
int lo = 0, hi = q.size();
vector<int> c;
while(lo++ < hi)
{
TreeNode *t = q.front();
q.pop();
c.push_back(t->val);
if(t->left) q.push(t->left);
if(t->right) q.push(t->right);
}
vec.push_back(c);
}
return vec;
}
};
法二:(按之字形打印用两个栈,按顺序打印就用两个队列!这样比较好写好记~)
//两个队列交错打印
class Solution {
public:
vector<vector<int> > Print(TreeNode* pRoot) {
vector<vector<int>> ret;
if(pRoot==NULL) return ret;
queue<TreeNode*> q1;
queue<TreeNode*> q2;
q1.push(pRoot);
while(!q1.empty()||!q2.empty()){
vector<int> v1;
vector<int> v2;
while(!q1.empty()){
v1.push_back(q1.front()->val);
if(q1.front()->left!=NULL) q2.push(q1.front()->left);
if(q1.front()->right!=NULL) q2.push(q1.front()->right);
q1.pop();
}
if(v1.size()!=0)
ret.push_back(v1);
while(!q2.empty()){
v2.push_back(q2.front()->val);
if(q2.front()->left!=NULL) q1.push(q2.front()->left);
if(q2.front()->right!=NULL) q1.push(q2.front()->right);
q2.pop();
}
if(v2.size()!=0)
ret.push_back(v2);
}
return ret;
}
};
法三:用LinkedList实现
/*
* 队列LinkedList完成层序遍历,用end记录每层结点数目
*/
public class Solution {
ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
if(pRoot == null){
return result;
}
Queue<TreeNode> layer = new LinkedList<TreeNode>();
ArrayList<Integer> layerList = new ArrayList<Integer>();
layer.add(pRoot);
int start = 0, end = 1;
while(!layer.isEmpty()){
TreeNode cur = layer.remove();
layerList.add(cur.val);
start++;
if(cur.left!=null){
layer.add(cur.left);
}
if(cur.right!=null){
layer.add(cur.right);
}
if(start == end){
end = layer.size();
start = 0;
result.add(layerList);
layerList = new ArrayList<Integer>();
}
}
return result;
}
}