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

2019-06-26  本文已影响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;
            }
        }
    }
上一篇下一篇

猜你喜欢

热点阅读