二叉树打印

来源:互联网 发布:mysql oxc000007b 编辑:程序博客网 时间:2024/06/05 03:26
题目:

有一棵二叉树,请设计一个算法,按照层次打印这棵二叉树。

给定二叉树的根结点root,请返回打印结果,结果按照每一层一个数组进行储存,所有数组的顺序按照层数从上往下,且每一层的数组内元素按照从左往右排列。保证结点数小于等于500。


public int[][] printTree(BTree root){if(root==null) return null;BTree last=root;//last和nlast标注当前行的最后节点,和下一行的最后节点。BTree nlast=root;ArrayList<Integer> row=new ArrayList();ArrayList<ArrayList<Integer>> res=new ArrayList();Queue<BTree> queue=new LinkedList();queue.add(root);while(!queue.isEmpty()){BTree q=queue.poll();//System.out.println("q.data="+q.data);row.add(q.data);if(q.left!=null){nlast=q.left;queue.add(q.left);}if(q.right!=null){nlast=q.right;queue.add(q.right);}if(q==last){res.add(new ArrayList(row));//这里注意,不能直接是res.add(row),row.clear();last=nlast;}}int[][] out=new int[res.size()][];for(int i=0;i<res.size();i++){int maxRow=res.get(i).size();out[i]=new int[maxRow];for(int j=0;j<maxRow;j++){out[i][j]=res.get(i).get(j);System.out.print(out[i][j]+"\t");}System.out.println();}return out;}


原创粉丝点击