二叉树准备:
public class TreeNode {int val;TreeNode left;TreeNode right;TreeNode() {}TreeNode(int val) {this.val = val;}TreeNode(int val, TreeNode left, TreeNode right) {this.val = val;this.left = left;this.right = right;}
}
思路:我们需要创建一个队列,根先进,如果左子树或者右子树不为空,也要进
力扣
public class Test2{public List<List<Integer>> levelOrder(TreeNode root) {Queue<TreeNode> qu=new LinkedList<>();List<List<Integer>> ret=new ArrayList<>();if(root==null)return ret;//队列存第一个qu.offer(root);int size;while (!qu.isEmpty()){List<Integer> list=new ArrayList<>();//队列不为空其中我们只返回当下跟节点的左子树第一个和右子树第一个,所以需要sizesize= qu.size();while (size!=0){TreeNode cur=qu.poll();list.add(cur.val);if(cur.left!=null)qu.add(cur.left);if(cur.right!=null)qu.add(cur.right);size--;}ret.add(list);//每一行}return ret;}
}