您的位置:首页 > 理论基础 > 数据结构算法

数据结构与算法学习记录--按层次打印二叉树结点的值

2018-03-01 19:24 344 查看
(from 牛客)

解题关键:找到当前结点所在行的最后一个结点last,找到下一行的最后一个结点nlast。层次遍历要使用队列。

初始状态:将last和nlast都指向第一个结点,将第一个结点放入队列。

以下操作在队列不为空的情况下进行:

获取队列中第一个元素,判断是否有左子树,有的话将其入队列,令nlast为左子树;判断是否有右子树,有的话将其入队列,令nlast为右子树;

判断当前结点是否为当前行的最后一个结点,即是否为last。是的话就打印标记(如打印空格)表示当前行结束,同时last指向nlast(能确定nlast一定是下一行的最后一个结点的原因是last的左右子树此时已经遍历完毕,即下一行全部结点均遍历完毕);不是则执行队列不为空时的第一步。

以下代码实现以上功能并把树中结点的值存入二维数组中,需要创建ArrayList动态二维数组临时存放树的遍历结果,然后再存入二维数组中。

/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}*/
public class TreePrinter {
public int[][] printTree(TreeNode root) {
// write code here
Queue<TreeNode> queue = new LinkedList<>();
TreeNode last = root;
TreeNode nlast = root;
queue.offer(root);
ArrayList<ArrayList<Integer>> raws= new ArrayList<>();
ArrayList<Integer> count = new ArrayList<>();
while(!queue.isEmpty()){
TreeNode node = queue.poll();
count.add(node.val);
if(node.left!=null){
nlast = node.left;
queue.offer(node.left);
}
if(node.right!=null){
nlast = node.right;
queue.offer(node.right);
}
if(node == last){
last = nlast;
raws.add(count);
count = new ArrayList<>();
}
}
int[][] list = new int[raws.size()][];
for(int i = 0;i<raws.size();i++){
count = raws.get(i);
int j = 0;
list[i] = new int[count.size()];
for(int number : count){
list[i][j++] = number;
}
}
return list;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐