Preorder Traversal | Practice | GeeksforGeeks

Given a binary tree, find its preorder traversal.
Example 1:
Input:
        1      
      /          
    4    
  /    \   
4       2
Output: 1 4 4 2 

Example 2:
Input:
       6
     /   \
    3     2
     \   / 
      1 2
Output: 6 3 1 2 2 


Your Task:
You just have to complete the function preorder() which takes the root node of the tree as input and returns an array containing the preorder traversal of the tree.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 <= Number of nodes <= 104
0 <= Data of a node <= 105
0
superrhitik4582 days ago
vector<int> vi;void pre(Node* root){    if(root!=NULL){         vi.push_back(root->data); pre(root->left); pre(root->right);} return;}vector <int> preorder(Node* root){ // Your code herepre(root); vector<int> res=vi;//v=vi;
vi.clear();// for(int i=0;i<v.size();i++)//cout<<v[i]<<" ";return res;}
0
itachinamikaze2211 week ago
JAVA
static ArrayList<Integer> preorder(Node root)   {              ArrayList<Integer> res= new ArrayList<>();       if(root==null)           return res;       Stack<Node> st= new Stack<Node>();       st.push(root);       while(st.isEmpty()==false)       {           root=st.pop();           res.add(root.data);           if(root.right!=null)               st.push(root.right);           if(root.left!=null)               st.push(root.left);       }   return res;}
+1
singh.shobhit0071 week ago
If someone is wondering why there solution is not working when they are declaring a global vector, it cause there are multiple entries for being made in the vector for different testcases and the array is not being cleared, use array.clear to clean your array before using that assign the value of array to a temp vector and return the temp, it should work 
 
for reference
vector<int> arr;void preOrder(Node *root){   if(root == nullptr)       return;   arr.push_back(root->data);;   preOrder(root->left);   preOrder(root->right);   return;}
vector <int> preorder(Node* root){ // Your code here preOrder(root); vector<int> res = arr; arr.clear(); return res;}
0
harshscode2 weeks ago
void findpre(Node *root,vector<int> &v){   if(!root)   return;   v.push_back(root->data);   findpre(root->left,v);   findpre(root->right,v);   }//Function to return a list containing the preorder traversal of the tree.vector <int> preorder(Node* root){    vector<int> v;    findpre(root,v);        return v;     }
0
hharshit81182 weeks ago
vector<int> preorder(Node* root){vector<int> v;stack<Node*> st;st.push(root);while(st.empty() == false){   Node* curr = st.top();   st.pop();   v.push_back(curr->data);   if(curr->right){       st.push(curr->right);   }   if(curr->left){       st.push(curr->left);   }}return v;}
0
mangy007
This comment was deleted.
0
meanm0nst3r2 weeks ago
What's the error?someone please commentCode:vector <int> preorder(Node* root){ // Your code here Node* curr=root; vector<int> v; if(!curr) return v;  v.push_back(curr->data); preorder(curr->left); preorder(curr->right); return v;}
0
sagrikasoni3 weeks ago
JAVA Solution
  static ArrayList<Integer> preorder(Node root)
    {
        ArrayList<Integer> arr = new ArrayList<Integer>();
       if(root==null) return arr;
     Stack<Node> q = new Stack<Node>();
       q.push(root);
       while(!q.isEmpty()){
           Node curr = q.pop();
           arr.add(curr.data);
           if(curr.right!=null)
           q.push(curr.right);
           if(curr.left!=null)
           q.push(curr.left);
           
       }
     
       return arr;
    }
0
talmeezahmed7864 weeks ago
#Iterative python solution, for more performance 
#replace the queue with deque

def preorder(root):
   
    # code here
    result = []

    # initialize our process queue
    queue = []
    size = 0

    # push the root node to our queue
    queue.append(root)
    size = size + 1

    while (size > 0):

        # process the node at front of queue
        currentNode = queue[0]
        queue = queue[1:]
        size = size - 1

        # process the root first
        if (currentNode.data != None):
            result.append(currentNode.data)
            
        # process the right node
        if (currentNode.right and currentNode.right.data != None):
            queue.insert(0, currentNode.right)
            size = size + 1
            
        # process the left node
        if (currentNode.left and currentNode.left.data != None):
            queue.insert(0, currentNode.left)
            size = size + 1

        

    return result

0
bsbh20is1 month ago
int arr[10000];
void pre(struct Node*node,int *i){   if(node==NULL)     return;   arr[(*i)]=node->data;   (*i)=(*i)+1;      pre(node->left,i);   pre(node->right,i);   }
int* preorder(struct Node* root){   //code here   int ind=0;   pre(root,&ind);   return arr;     //do not change the default values(i.e -1) in the unused array indices.}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.