重新建了一个Node数据结构,Node{TreeNode 树节点,level 层次},进行层次遍历BFS。
书上的用两个变量控制将每层树节点打印到一行,很nice~
import java.util.ArrayList; import java.util.LinkedList; import java.util.Queue; class Node { TreeNode treeNode; int level; public Node(TreeNode treeNode, int level) { this.treeNode = treeNode; this.level = level; } } public class Solution { ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) { ArrayList<ArrayList<Integer>> list = new ArrayList<>(); Queue<Node> queue = new LinkedList<>(); if (pRoot == null) { return list; } queue.add(new Node(pRoot, 1)); ArrayList<Integer> arraylist = new ArrayList<>(); int level = 1; while (!queue.isEmpty()) { Node node = queue.remove(); if (node.level != level) { list.add(arraylist); arraylist = new ArrayList<>(); level++; } arraylist.add(node.treeNode.val); if (node.treeNode.left != null) { queue.add(new Node(node.treeNode.left, node.level + 1)); } if (node.treeNode.right != null) { queue.add(new Node(node.treeNode.right, node.level + 1)); } } list.add(arraylist); return list; } }