> For the complete documentation index, see [llms.txt](https://soumyajit4419.gitbook.io/ds-algo/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://soumyajit4419.gitbook.io/ds-algo/binary-tree/tree-traversals/pre-order-traversal.md).

# 2.Pre-order Traversal

Pre means root at first.

Pre-order traversal is to visit the root first. Then traverse the left subtree. Finally, traverse the right subtree.

**Preorder traversal is used to create a copy of the tree**

## Iterative Method using stack

**Steps:**\
&#x20;`1. Print a node`\
`2. Add the address to stack`\
`2. Move to left subtree`\
`3. Move to right subtree`&#x20;

```cpp
class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) {
        
        vector<int> v;
        TreeNode *t = root;
        stack <TreeNode*> s;
        
        while(t!=NULL || !s.empty()){
            
            if(t!=NULL){
                v.push_back(t->val);
                s.push(t);
                t = t->left;
            }
            else{
                t = s.top();
                s.pop();
                t = t->right;
            }
            
        }
        return v;
        
    }
};
```

## Recursive method

```cpp
class Solution
{
public:
    vector<int> v;
    void preorder(TreeNode *t)
    {
        if (t == NULL){
            return;
        }
        v.push_back(t->val);
        preorder(t->left);
        preorder(t->right);
    }

    vector<int> preorderTraversal(TreeNode *root)
    {
        preorder(root);
        return v;
    }
};
```
