DSA Day 87/100

DSA Day 87/100

Topic: Tree

1) Recursive Post Order Traversal

Easy

2) Iterative Pre-Order Traversal - GFG

Medium

RECURSION

Input:
        19
     /     \
    10      8
  /    \
 11    13
Output: 11 13 10 8 19
 ArrayList<Integer> postOrder(Node root)
    {
        ArrayList<Integer> temp_arr = new ArrayList<>();

        if(root!=null){

            temp_arr.addAll(postOrder(root.left));
            temp_arr.addAll(postOrder(root.right));
            temp_arr.add(root.data);
        }
        return temp_arr;
    }

Iterative Pre-Order Traversal - GFG

Input:
           1
         /   \
        2     3
      /  \
     4    5
Output: 1 2 4 5 3
Explanation:
Preorder traversal (Root->Left->Right) of 
the tree is 1 2 4 5 3.
 ArrayList<Integer> preOrder(Node root)
    {
        ArrayList<Integer> temp_arr = new ArrayList<>();
        Stack <Node> temp_stack = new Stack<>();

        temp_stack.push(root);

        while(!temp_stack.isEmpty()){

            Node popped_address = temp_stack.pop();
            temp_arr.add(popped_address.data);
            if(popped_address.right!=null){
                temp_stack.push(popped_address.right);
            }
            if(popped_address.left!=null){
                temp_stack.push(popped_address.left);
            }
        }
        return temp_arr;
    }

Thank you for reading :)