107. Binary Tree Level Order Traversal II
BFS
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
LinkedList<List<Integer>> result = new LinkedList<>();
if (root == null) {
return result;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int qsize = queue.size();
List<Integer> list = new ArrayList<>();
for (int q = 0; q < qsize; q++) {
TreeNode cur = queue.poll();
if (cur == null) {
continue;
}
list.add(cur.val);
queue.offer(cur.left);
queue.offer(cur.right);
}
if (!list.isEmpty()) {
result.offerFirst(list);
}
}
return result;
}
}
DFS
class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
LinkedList<List<Integer>> result = new LinkedList<>();
dfs(root, 0, result);
return result;
}
private void dfs(TreeNode node, int level, LinkedList<List<Integer>> result) {
if (node == null) {
return;
}
if (level >= result.size()) {
result.offerFirst(new LinkedList<>()); // add new list in the front side
}
result.get(result.size() - level - 1).add(node.val); // almost like, always add in head one
dfs(node.left, level+1, result);
dfs(node.right, level+1, result);
}
}
Last updated