You are viewing a single comment's thread. Return to all 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); }
Seems like cookies are disabled on this browser, please enable them to open this website
Tree: Preorder Traversal
You are viewing a single comment's thread. Return to all comments →