美文网首页
【剑指offer】层序打印二叉树

【剑指offer】层序打印二叉树

作者: 蛋花汤汤 | 来源:发表于2019-06-26 08:48 被阅读0次
        // 层序遍历二叉树
        public void printTreeByLevel(TreeNode root){
    
            if(root == null)
                return;
    
            Queue<TreeNode> q = new LinkedList<>(); // 用来暂存遍历的节点
            q.offer(root);
    
            int current = 1; // 用来记录当前层还需要打印的节点数目
            int next = 0; // 用来记录下一层需要打印的节点数目
    
            while(!q.isEmpty()){
                TreeNode tmp = q.poll();
                System.out.print(tmp.val + " ");
                current --;
                if(tmp.left != null){
                    q.offer(tmp.left);
                    next ++;
                }
                if(tmp.right != null){
                    q.offer(tmp.right);
                    next ++;
                }
                if(current == 0){   // 到达层尾后,换行,更新计数
                    System.out.println();
                    current = next;
                    next = 0;
                }
            }
        }
    

    相关文章

      网友评论

          本文标题:【剑指offer】层序打印二叉树

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