Tree:从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。

ArrayList> Print(TreeNode pRoot) {
        
        ArrayList> arrayLists = new ArrayList>();
        if (pRoot==null) {
            return arrayLists;
        }
        Queue queue = new LinkedList();
        queue.add(pRoot);
        while (!queue.isEmpty()) {
            ArrayList arrayList = new ArrayList();
            int count = queue.size();
            for (int i = 0; i < count; i++) {
                if (queue.peek().left!=null) {
                    queue.add(queue.peek().left);
                }
                if (queue.peek().right!=null) {
                    queue.add(queue.peek().right);
                }
                arrayList.add(queue.poll().val);
            }
            arrayLists.add(arrayList);
        }
        return arrayLists;
    }

你可能感兴趣的:(Tree:从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。)