Question : Given the root of a binary tree, return the preorder traversal of its nodes values.
I solved this using iterative way, where I had used 'top.state++' instead to 'state++' and I got my answer. But unable to get answer when I was using 'state++'. Can anyone tell me why is it so?
class Solution {
class Pair {
TreeNode root;
int state;
Pair(TreeNode root,int state) {
this.root = root;
this.state = state;
}
}
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> al = new ArrayList<>();
if(root == null) return al;
Stack<Pair> stack = new Stack<>();
stack.push(new Pair(root,1));
while(!stack.isEmpty()) {
Pair top = stack.peek();
int state = top.state;
TreeNode curr = top.root;
if(state == 1) {
al.add(curr.val);
top.state++; // why top.state++, why not state++ ?
if(curr.left != null) stack.push(new Pair(curr.left,1));
}
else if(state == 2) {
top.state++;
if(curr.right != null) stack.push(new Pair(curr.right,1));
}
else {
stack.pop();
}
}
return al;
}
}
Because int state = top.state
is a local variable that copies the value of top.state
. It does not share the same location in memory. Therefore, changing the value of the local variable will not change the value of the top.state
field.
See this for more information https://java-programming.mooc.fi/part-5/3-primitive-and-reference-variables
Declaring a primitive variable causes the computer to reserve some memory where the value assigned to the variable can be stored. The size of the storage container reserved depends on type of the primitive. In the example below, we create three variables. Each one has its own memory location to which the value that is assigned is copied.
int first = 10;
int second = first;
int third = second;
System.out.println(first + " " + second + " " + third);
second = 5;
System.out.println(first + " " + second + " " + third);
Which prints:
10 10 10
10 5 10
The name of the variable tells the memory location where its value is stored. When you assign a value to a primitive variable with an equality sign, the value on the right side is copied to the memory location indicated by the name of the variable. For example, the statement int first = 10 reserves a location called first for the variable, and then copies the value 10 into it.
Similarly, the statement int second = first; reserves in memory a location called second for the variable being created and then copies into it the value stored in the location of variable first.