We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Tree: Preorder Traversal
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); }
+ 0 comments void preOrder(Node *root) { if(root) { cout<data<<" "; preOrder(root->left); preOrder(root->right); } }
+ 0 comments ** java iterative solution using stack**
public static void preOrder(Node root) {
Stack<Node> s = new Stack<Node>(); Node curr = root; if(curr==null){ return; } while(curr!=null||s.size()>0){ while(curr!=null){ s.push(curr); System.out.print(curr.data+" "); curr=curr.left; } curr= s.pop(); curr=curr.right; } }
+ 0 comments print(root.info, end=" ") if root.left: preOrder(root.left) if root.right: preOrder(root.right)
+ 0 comments "Our test code passes the root node of a binary tree to the preOrder function."
Yeah... That's not true for quite a lot of the languages I can choose from. What does input "1 2 3 4 5 6" on stdin mean?
Load more conversations
Sort 424 Discussions, By:
Please Login in order to post a comment