美文网首页
Java日记2018-06-03

Java日记2018-06-03

作者: hayes0420 | 来源:发表于2018-06-03 08:03 被阅读0次

    32.1 从上往下打印二叉树
    使用一个辅助的队列,来打印先后的数字,今天学习到的一点是LinkedList实现queue的接口,所以可以使用queue的陷入先出的特性。学习了一下,发现居然也实现了stack的方法,真是相当奇怪的。

    //从上往下打印二叉树
        private static LinkedList<TreeNode> que = new LinkedList<TreeNode>();
        public static void printtree(TreeNode root){
            if(root!=null) que.add(root);
            TreeNode temp = null;
            while(que.peek()!=null) {
                System.out.println(que.peek().val);
                temp=que.poll();
                if(temp.left!=null) que.add(temp.left);
                if(temp.right!=null) que.add(temp.right);
            }
        }
    

    32.2 把二叉树打印成多行
    几乎等于上边的,但是怎么分割打印,增加两个整数计算层,还是有点绕的

    // 打印成多行
        public static void printtreeM(TreeNode root) {
            if (root != null)
                que.add(root);
            TreeNode temp = null;
            int count = 0;//记录当前层已经打印的个数
            int last = 0;//记录当前层一个有多少个
            while (!que.isEmpty()) {
                last = que.size();
                count = 0;
                while (count < last) {
                    System.out.print(que.peek().val);
                    temp = que.poll();
                    if (temp.left != null)
                        que.add(temp.left);
                    if (temp.right != null)
                        que.add(temp.right);
                    count++;
                }
                System.out.println();
            }
        }
    

    相关文章

      网友评论

          本文标题:Java日记2018-06-03

          本文链接:https://www.haomeiwen.com/subject/xpnrsftx.html