数据结构定义:
// Definition for a binary tree node.
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;
}
}
算法:
//每次遍历都是一层数据
//定义一个队列,队列初始的大小就是一层的数据大小
//每次循环都从头拿数据,并将子树放入队列中
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
LinkedList<TreeNode> queue =new LinkedList<>();
if(root == null){
return result;
}
queue.add(root);
while(!queue.isEmpty()){
int size = queue.size();
List<Integer> temp =new ArrayList<>();
for(int i =0;i<size;i++){
TreeNode node =queue.removeFirst();
temp.add(node.val);
if(node.left != null){
queue.add(node.left);
}
if(node.right != null){
queue.add(node.right);
}
}
result.add(temp);
}
return result;
}
}