# Two Java Solutions, Recursive and Iterative

• ``````
public List<List<Integer>> levelOrderBottomV1(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
List<TreeNode> parentLevel = new ArrayList<>();
List<TreeNode> thisLevel = new ArrayList<>();
if (root != null)
while (!parentLevel.isEmpty()) {
thisLevel.clear();
List<Integer> valueList = new ArrayList<>();
for (TreeNode node : parentLevel) {
if (node != null) {
if (node.left != null)
if (node.right != null)
}
}
parentLevel.clear();
}
return result;
}

public List<List<Integer>> levelOrderBottomV2(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
treeWalkThrough(result, root, 1);
Collections.reverse(result);
return result;
}

private void treeWalkThrough(List<List<Integer>> result, TreeNode node, int depth) {
if (node != null) {
if (result.size() < depth) // it is the first node of this level

depth++;
treeWalkThrough(result, node.left, depth);
treeWalkThrough(result, node.right, depth);
}
}
``````

• In my opinion, if we insert something in an ArrayList at some specific index, there will be a lot of time overhead. As we need to move the elements and then insert. I am referring to this line:

``````result.add(0,  valueList);
``````

• @mandalapusc.edu Oh thanks, therefore a LinkedList is preferable here

• @keZhenxu There many ways to do this, IMO using LinkedList is one of the good options.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.