class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res=new ArrayList<>();
if(root==null) return res;
List<Integer>list=new ArrayList<>();
Queue<TreeNode>queue=new LinkedList<>();
queue.add(root);
while(!queue.isEmpty()){
int n=queue.size();
for(int i=0;i<n;i++){
TreeNode cur=queue.poll();
list.add(cur.val);
if(cur.left!=null)queue.add(cur.left);
if(cur.right!=null) queue.add(cur.right);
}
res.add(new ArrayList<>(list));
list.clear();
}
return res;
}
}
比较传统的BFS,在每一层将结果添加到集合中,并且清空集合
最新推荐文章于 2024-08-15 05:02:54 发布