- 从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
- 层次遍历即可
- 可设置两个变量cur和next,分别记录当前遍历层的个数及记录下一层的个数
- Java代码
import java.util.*;
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
if(pRoot==null) return res;
Queue<TreeNode> q = new LinkedList<>();
ArrayList<Integer> tmp = new ArrayList<>();
int cur = 1;
int next =0;
q.add(pRoot);
while(!q.isEmpty()){
TreeNode node = q.remove();
tmp.add(node.val);
cur--;
if(node.left != null) {
q.add(node.left);
next++;
}
if(node.right != null){
q.add(node.right);
next++;
}
if(cur==0){
res.add(new ArrayList<Integer>(tmp));
tmp.clear();
cur = next;
next = 0;
}
}
return res;
}
}
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
vector<vector<int> > Print(TreeNode* pRoot) {
vector<vector<int>> res;
vector<int> res_line;
queue<TreeNode*> tmp;
queue<int> height;
int pre=1;
if(pRoot==NULL) return {};
tmp.push(pRoot);
height.push(1);
while(!tmp.empty())
{
if(height.front()==pre)
res_line.push_back(tmp.front()->val);
else
{
res.push_back(res_line);
res_line.clear();
res_line.push_back(tmp.front()->val);
}
if(tmp.front()->left)
{
tmp.push(tmp.front()->left);
height.push(height.front()+1);
}
if(tmp.front()->right)
{
tmp.push(tmp.front()->right);
height.push(height.front()+1);
}
pre=height.front();
tmp.pop();
height.pop();
}
res.push_back(res_line);
return res;
}
};
网友评论