二叉树的层次遍历

102. 二叉树的层序遍历

给你二叉树的根节点 root ,返回其节点值的 层序遍历 。 (即逐层地,从左到右访问所有节点)。

示例 1:

输入:root = [3,9,20,null,null,15,7]
输出:[[3],[9,20],[15,7]]

示例 2:

输入:root = [1]
输出:[[1]]

示例 3:

输入:root = []
输出:[]

提示:

树中节点数目在范围 [0, 2000] 内
-1000 <= Node.val <= 1000

代码

迭代法

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
class Solution {

public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> ans = new ArrayList<>();
if(root == null) return ans;
Deque<TreeNode> que = new ArrayDeque<>();

que.offer(root);
while( !que.isEmpty() ){
int size = que.size();
List<Integer> path = new ArrayList<>();
for(int i = 0; i < size; i++){
TreeNode node = que.poll();
path.add(node.val);
if(node.left != null){
que.offer(node.left);
}
if(node.right != null){
que.offer(node.right);
}
}
ans.add(new ArrayList<>(path));
}
return ans;
}
}

二叉树的层次遍历
http://example.com/2023/03/30/算法/二叉树/4. 二叉树的层序遍历/
作者
PALE13
发布于
2023年3月30日
许可协议