educative.io

Reverse Level Order traversal Java solution problem

Hi!
I wanted to ask why do you have to declare the size of each arraylist you make to store each level:
List currentLevel = new ArrayList<>(levelSize); (line 23).
I can see that not declaring the size will throw an exception : " java.lang.OutOfMemoryError: Java heap space" but I can’t really understand why. (And almost the same question, the regular level order traversal, you didn’t declare for the size and everything went smooth with no exceptions).
Thanks!

Hi, 11120!
Can you please provide links to the course and lesson?

Hi Isra_Javaid,
Actually I’ve made a dummy mistake and this was the reason for the bug.
It is part of the “Grokking the Coding Interview: Patterns for Coding Questions” course if you still want to know.
I don’t need any help anymore, so if there’s admins here you can remove the post.

Hi @11120
In the code List currentLevel = new ArrayList<>(levelSize); levelSize is actually the size of binary tree which is declared explicitly.In the explicit declaration, we define the initial capacity of arraylist but this doesn’t mean that we cannot add more elements. So as you keep on adding more elements than levelsize, the size of the list keeps increasing. However, it is good practice to define the size of arraylist.
In short, providing initial capacity won’t really change anything in terms of size.
If we create an object of arraylist with implicit size declaration,
List<List<Integer>> result = new LinkedList<List<Integer>>(); it won’t give an error as you can see in the following screenshot.

Hope it will help you in understanding. Happy Learning :blush: