Tree: Preorder Traversal

  • + 0 comments
    #include <string>
    #include <cstring>
    #include <iostream>
    #include <iomanip>
    #include <vector>
    #include <algorithm>
    #include <sstream>
    #include <map>
    #include <set>
    #include <cmath>
    #include <fstream>
    using namespace std;
    using ll = long long;
    const int MOD =1e9+7;
    
    
    //BST
    //search,insert,delete: O(logn) average
    //worst:O(n)
    struct Node
    {
        int val;
        Node *left,*right;
        Node(int x)
        {
            val=x;
            left=right=NULL;
        }
    };
    Node* insert(Node *root,int x)
    {
        if(root==NULL)
            return new Node(x);
        if(x<root->val)
            root->left=insert(root->left,x);
        else
            root->right=insert(root->right,x);
        return root;
    }
    void preorder(Node *root)
    {
        if(root==NULL)
            return;
        cout<<root->val<<' ';
        preorder(root->left);
        preorder(root->right);
    }
    int main() {
        ios::sync_with_stdio(false);
        cin.tie(nullptr);
        cout.tie(nullptr);
    
        Node *root=NULL;
        int n; cin>>n;
        for(int i=0;i<n;i++)
        {
            int x;cin>>x;
            root=insert(root,x);
        }
        preorder(root);
    }