LeetCode107-二叉树的层序遍历II

LeetCode107-二叉树的层序遍历II

直接使用链表头插法返回

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> res = new LinkedList<>();
if (root == null) return res;
Deque<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int n = queue.size();
List<Integer> level = new LinkedList<>();
for (int i = 0; i < n; i++) {
TreeNode poll = queue.poll();
level.add(poll.val);
TreeNode left = poll.left, right = poll.right;
if (left != null) {
queue.offer(poll.left);
}
if (right != null) {
queue.offer(poll.right);
}
}
res.add(0, level);
}
return res;
}

借助栈

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
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> res = new LinkedList<>();
if (root == null) return res;
Queue<TreeNode> queue = new LinkedList<>();
Stack<List<Integer>> stack = new Stack<>();
queue.offer(root);
while (!queue.isEmpty()) {
int n = queue.size();
List<Integer> level = new LinkedList<>();
for (int i = 0; i < n; i++) {
TreeNode poll = queue.poll();
level.add(poll.val);
if (poll.left != null) {
queue.offer(poll.left);
}
if (poll.right != null) {
queue.offer(poll.right);
}
}
stack.push(level);
}
while (!stack.isEmpty()){
res.add(stack.pop());
}
return res;
}