
题目
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
解题思路
二叉树层序遍历
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
|
import java.util.ArrayList; import java.util.LinkedList; public class { ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) { ArrayList<ArrayList<Integer>> AA = new ArrayList<>(); if(pRoot == null){ return AA; } LinkedList<TreeNode> nodeList = new LinkedList<>(); nodeList.add(pRoot); while(!nodeList.isEmpty()){ ArrayList<Integer> A = new ArrayList<>(); int size = nodeList.size(); for(int i = 0; i < size; ++i){ TreeNode node = nodeList.removeFirst(); A.add(node.val); if(node.left != null){ nodeList.addLast(node.left); } if(node.right != null){ nodeList.addLast(node.right); } } AA.add(A); } return AA; } }
|
近期评论