declaration of List outside of the method: leetcode 965 Univalued Binary Tree

Viewed 14

I don't understand why we need to declare the List vals outside of the method? enter image description here

Can someone explain List vals; and vals = new ArrayList();? why can we new Arraylist like this: vals = new ArrayList();

My initial way of solving this problem is: enter image description here

1 Answers

dfs needs access to vals. In your version of the code the scope of vals is limited to the isUnitvalTree function. It is a local variable there.

The first code you presented solves this by extending the scope of that variable to the instance of the class. Because this instance will be used to call your function usUnivalTree multiple times, it is then necessary to clear the array as it will still have the values from a previous run. That's why that version has the assignment vals = new ArrayList().

Another way to give dfs access to that array, is to define it locally like you did, but then to pass it as argument to dfs -- which should then have an extra parameter for receiving the reference to that array. And each recursive call should then also pass that array.

Related