1. 题目描述(简单难度)
[success] 102. 二叉树的层序遍历
2. 解法一:使用队列进行层序遍历
先巩固一下层序遍历输出
class Solution {
public static void main(String[] args) {
TreeNode t1 = new TreeNode(3);
TreeNode t2 = new TreeNode(9);
TreeNode t3 = new TreeNode(20);
TreeNode t4 = new TreeNode(15);
TreeNode t5 = new TreeNode(7);
t1.left = t2;
t1.right = t3;
t2.left = t4;
t2.right = t5;
List<Integer> resp = levelOrder(t1);
resp.forEach(System.out::println);
}
public static List<Integer> levelOrder(TreeNode root) {
Deque<TreeNode> deque = new LinkedList<>();
deque.offer(root);
List<Integer> res = new ArrayList<>();
while (!deque.isEmpty()) {
TreeNode levelRoot = deque.poll();
res.add(levelRoot.val);
if (levelRoot.left != null) {
deque.offer(levelRoot.left);
}
if (levelRoot.right != null) {
deque.offer(levelRoot.right);
}
}
return res;
}
}
本题解题思路: BFS
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
if (null == root) {
return new ArrayList<>();
}
Deque<TreeNode> deque = new LinkedList<>();
deque.offer(root);
List<List<Integer>> resp = new ArrayList<>();
while (!deque.isEmpty()) {
List<Integer> ans = new ArrayList<>();
int level = deque.size();
for (int i = 0; i < level; i++) {
TreeNode poll = deque.poll();
ans.add(poll.val);
if (poll.left != null) {
deque.offer(poll.left);
}
if (poll.right != null) {
deque.offer(poll.right);
}
}
resp.add(ans);
}
return resp;
}
}