2024.2.17
- 题目来源
- 我的题解
- 方法一 广度优先搜索(队列实现)
题目来源
力扣每日一题;题序:429
我的题解
方法一 广度优先搜索(队列实现)
和二叉树的层序遍历相同,只是在添加子节点的细节有所不同
时间复杂度:O(n)
空间复杂度:O(n)
public List<List<Integer>> levelOrder(Node root) {List<List<Integer>> res=new ArrayList<>();if(root==null)return res;Queue<Node> queue=new LinkedList<>();queue.offer(root);while(!queue.isEmpty()){int sz=queue.size();List<Integer> list=new ArrayList<>();for(int i=0;i<sz;i++){Node t=queue.poll();list.add(t.val);//加入子节点的细节for(Node node:t.children){queue.offer(node);}}res.add(list);}return res;
}
有任何问题,欢迎评论区交流,欢迎评论区提供其它解题思路(代码),也可以点个赞支持一下作者哈😄~