您的位置:首页 > 其它

关于二叉树的按层打印

2016-09-04 21:58 183 查看
本文的思路来自于牛客网左程云大大的二叉树视频

视频地址

http://www.nowcoder.com/courses/1/1/1

题目要求如下:



至于算法分析,大家看视频吧,左老大讲的肯定比我清楚,下面是我实现的代码

class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;

public TreeNode(int val) {
this.val = val;
}

}

public class Solution {
public static void main(String[] args) {
TreeNode t1=new TreeNode(1);
TreeNode t2=new TreeNode(2);
TreeNode t3=new TreeNode(3);
TreeNode t4=new TreeNode(4);
TreeNode t5=new TreeNode(5);
TreeNode t6=new TreeNode(6);
TreeNode t7=new TreeNode(7);
TreeNode t8=new TreeNode(8);

t1.left=t2;  t1.right=t3;
t2.left=t4;  t3.left=t5; t3.right=t6;
t5.left=t7;  t5.right=t8;
new Solution().printFromTopToBottom(t1);

}

public ArrayList<Integer> printFromTopToBottom(TreeNode root) {
ArrayList<Integer> list=new ArrayList<Integer>();
Queue <TreeNode> queue=new ArrayBlockingQueue<>(100);
TreeNode last=root;     //当前行的最后节点
TreeNode nLast=root;    //下一行的最右节点
queue.add(root);

while (!queue.isEmpty()) {
TreeNode out=queue.poll();
System.out.print(out.val+" ");
list.add(out.val);
if (out.left!=null) {
queue.add(out.left);
nLast=out.left;
}
if (out.right!=null) {
queue.add(out.right);
nLast=out.right;
}
if (out==last) {
System.out.println("");
last=nLast;
}

}
return list;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: