Simple Solution Using Stacks

// Preorder Traversal Using stack
public ArrayList<Integer> preorderTraversal(TreeNode A) {
        return new ArrayList<>();
    ArrayList<Integer> res = new ArrayList<>();
    Stack<TreeNode> st = new Stack<>();


        TreeNode node = st.pop();

    return res ;



how pushing right first in preorder gives us right answer …mindfucked !


in preorder, we process left first . In this case we push right then left ,so that left gets processed first(Since we use Stack).


Why can’t we use a queue here and like push the left first and then the right. All the other things same. I am getting wrong answer for that. I mean like for every node we are taking the root and then the left and right and pushing them in that order. It should work na even with the queue. Anyone help if you get it.


We can’t use a queue here because insertion in queue happens at the back and you are only able to access the front element. I believe doubly-ended queue can be used but the use of stack is highly intuitive.