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;
}
}