Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com

Tree Traversals

Easy
0/40
Average time to solve is 15m
profile
Contributed by
214 upvotes
Asked in companies
Wells FargoCognizantBig Basket

Problem statement

You have been given a Binary Tree of 'N'

nodes, where the nodes have integer values.


Your task is to return the ln-Order, Pre-Order, and Post-Order traversals of the given binary tree.


For example :
For the given binary tree:

Binary - Tree1

The Inorder traversal will be [5, 3, 2, 1, 7, 4, 6].
The Preorder traversal will be [1, 3, 5, 2, 4, 7, 6].
The Postorder traversal will be [5, 2, 3, 7, 6, 4, 1].
Detailed explanation ( Input/output format, Notes, Images )
Input Format :
The first line contains elements of the tree in the level order form. The line consists of values of nodes separated by a single space. In case a node is null, we take -1 in its place.
Example :
The input for the tree is depicted in the below image: 

BT - 2

1 3 8 5 2 7 -1 -1 -1 -1 -1 -1 -1

Explanation :

Level 1 :
The root node of the tree is 1

Level 2 :
Left child of 1 = 3
Right child of 1 = 8

Level 3 :
Left child of 3 = 5
Right child of 3 = 2
Left child of 8 =7
Right child of 8 =  null (-1)


Level 4 :
Left child of 5 = null (-1)
Right child of 5 = null (-1)
Left child of 2 = null (-1)
Right child of 2 = null (-1)
Left child of 7 = null (-1)
Right child of 7 = null (-1)

1
3 8
5 2 7 -1
-1 -1 -1 -1 -1 -1
Note :
1. The first not-null node(of the previous level) is treated as the parent of the first two nodes of the current level. The second not-null node (of the previous level) is treated as the parent node for the next two nodes of the current level and so on.

2. The input ends when all nodes at the last level are null(-1).

3. The above format was just to provide clarity on how the input is formed for a given tree. The sequence will be put together in a single line separated by a single space. Hence, for the above-depicted tree, the input will be given as:

1 3 8 5 2 7 -1 -1 -1 -1 -1 -1 -1
Output Format :
The first line of output contains 'N' single space-separated integers denoting the node's values in In-Order traversal.

The second line of output contains 'N' single space-separated integers denoting the node's values in Pre-Order traversal.

The third line of output contains 'N' single space-separated integers denoting the node's values in Post-Order traversal.
Note :
You don't need to print anything, it has already been taken care of. Just implement the given function.
Sample Input 1 :
1 2 3 -1 -1 -1  6 -1 -1
Sample Output 1 :
2 1 3 6 
1 2 3 6 
2 6 3 1
Explanation of Sample Output 1 :
 The given binary tree is shown below:

BT - 3

Inorder traversal of given tree = [2, 1, 3, 6]
Preorder traversal of given tree = [1, 2, 3, 6]
Postorder traversal of given tree = [2, 6, 3, 1]
Sample Input 2 :
1 2 4 5 3 -1 -1 -1 -1 -1 -1
Sample Output 2 :
5 2 3 1 4 
1 2 5 3 4 
5 3 2 4 1
Explanation of Sample Output 2 :
The given binary tree is shown below:

BT - 5

Inorder traversal of given tree = [5, 2, 3, 1, 4]
Preorder traversal of given tree = [1, 2, 5, 3, 4]
Postorder traversal of given tree = [5, 3, 2, 4, 1]
Constraints :
1 <= 'N' <= 10^5
0 <= 'data' <= 10^5     

where 'N' is the number of nodes and 'data' denotes the node value of the binary tree nodes.

Time limit: 1 sec
Hint

Think of a recursive solution.

Approaches (3)
Recursive Approach

The idea here is to use recursion for ln-Order, Pre-Order, and Post-Order traversal of a binary tree.

Steps :

Inorder traversal : 

void inOrder(‘NODE’):

  1. Visit the left subtree of ‘NODE’ i.e., call inOrder(‘NODE’ -> left).
  2. Visit node and if ‘NODE’ != NULL then add data of node to answer.
  3. Visit the right subtree of ‘NODE’ i.e, call inOrder(‘NODE’ -> right).

Preorder traversal :

void preOrder(‘NODE’): 

  1. Visit node and if ‘NODE’ != NULL then add data of node to answer.
  2. Visit the left subtree of ‘NODE’ i.e., call preOrder(‘NODE’ -> left).
  3. Visit the right subtree of ‘NODE’ i.e., call preOrder(‘NODE’ -> right).

Postorder traversal :

void postOrder(‘NODE’): 

  1. Visit the left subtree of ‘NODE’ i.e., call postOrder(‘NODE’->left).
  2. Visit the right subtree of node i.e., call postOrder(‘NODE’->right).
  3. Visit node and if ‘NODE’ != NULL then add data of node to answer.
Time Complexity

O(N), where ‘N’ is the total number of nodes in the given binary tree.

 

In the worst case, we are visiting each node exactly once in each of Inorder, Preorder, and Postorder traversals so we will visit 3 * ‘N’ nodes. Hence the overall time complexity will be O(N).

Space Complexity

O(N), where ‘N’ is the total number of nodes in the given binary tree.

 

In the worst case, when we have given a skew binary tree we need O(N) recursion calls. Hence the overall space complexity will be O(N).

Video Solution
Unlock at level 3
(75% EXP penalty)
Code Solution
(100% EXP penalty)
Tree Traversals
All tags
Sort by
Search icon

Interview problems

Easy C++ Solution || Tree Traversals

/*

    Following is Binary Tree Node structure:

    class TreeNode

    {

    public:

        int data;

        TreeNode *left, *right;

        TreeNode() : data(0), left(NULL), right(NULL) {}

        TreeNode(int x) : data(x), left(NULL), right(NULL) {}

        TreeNode(int x, TreeNode *left, TreeNode *right) : data(x), left(left), right(right) {}

    };

*/

void preOrder(vector<int>&pre,TreeNode*root){

    if(root == nullptr){

        return ;

    }

    pre.push_back(root->data);

    preOrder(pre ,root->left);

    preOrder(pre ,root->right);

}

void inOrder(vector<int>&ino,TreeNode*root){

    if(root == nullptr){

        return ;

    }

    inOrder(ino ,root->left);

    ino.push_back(root->data);

    inOrder(ino,root->right);

}

 

void PostOrder(vector<int>&post,TreeNode*root){

    if(root == nullptr){

        return ;

    }

    PostOrder(post,root->left);

    PostOrder(post,root->right);

    post.push_back(root->data);

}

 

vector<vector<int>> getTreeTraversal(TreeNode *root){

    // Write your code here.

    vector<int> ino, pre, post;

    inOrder(ino, root);

    PostOrder(post, root);

    preOrder(pre, root);

 

    vector<vector<int>>ans;

    ans.push_back(ino);

    ans.push_back(pre);

    ans.push_back(post);

    return ans; 

}

163 views
0 replies
0 upvotes

Interview problems

Easy Java Solution

import java.util.ArrayList;

import java.util.List;

public class Solution {

    public static List<List<Integer>> getTreeTraversal(TreeNode root) {

        // Write your code here.

        List<List<Integer>>res=new ArrayList<>();

        res.add(inOrder(root,new ArrayList<Integer>()));

        res.add(preOrder(root,new ArrayList<Integer>()));

        res.add(postOrder(root,new ArrayList<Integer>()));

        return res;

    }

    public static List<Integer> inOrder(TreeNode root,ArrayList<Integer>li){

        if(root==null){

            return li;

        }

        inOrder(root.left,li);

        li.add(root.data);

        inOrder(root.right,li);

        return li;

    }

    public static List<Integer> preOrder(TreeNode root,ArrayList<Integer>li){

        if(root==null){

            return li;

        }

        li.add(root.data);

        preOrder(root.left,li);

        preOrder(root.right,li);

        return li;

    }

    public static List<Integer> postOrder(TreeNode root,ArrayList<Integer>li){

        if(root==null){

            return li;

        }

        postOrder(root.left,li);

        postOrder(root.right,li);

        li.add(root.data);

        return li;

    }

}

134 views
0 replies
0 upvotes

Interview problems

A simple technque to solve this probleam

void f(TreeNode* root, vector<vector<int>> &vec){ //intlize the vectors

    if(root == NULL) return; //If root value NULL hoy

    vec[1].push_back(root->data); //Stack e root data IN korbo PREORDER

    f(root->left, vec); //Left side theke

    vec[0].push_back(root->data); //Stack e root data IN korbo INORDER

    f(root->right, vec);// right side theke

    vec[2].push_back(root->data); //Baki ta PostOrder

}

vector<vector<int>> getTreeTraversal(TreeNode *root)

{

    // Write your code here.  

    vector<vector<int>> ans(3); //Total 3 te answer int korbo

    f(root, ans); //2 to aslo

    return ans; //return korbo answer

}

225 views
0 replies
1 upvote

Interview problems

In a single traversal,no need to write separate code for all

void solve(TreeNode* root,vector<int>&pre,vector<int>&inorder,vector<int>&post){

    if(root==NULL)return;

    pre.push_back(root->data);

    solve(root->left,pre,inorder,post);

    inorder.push_back(root->data);

    solve(root->right,pre,inorder,post);

    post.push_back(root->data);

 

}

vector<vector<int>> getTreeTraversal(TreeNode *root){

    vector<int>pre,post,inorder;

    vector<vector<int>>ans;

    solve(root,pre,inorder,post);

    ans.push_back(inorder);

    ans.push_back(pre);

    ans.push_back(post);

    return ans;

}

367 views
0 replies
1 upvote

Interview problems

Tree Traversals Easy CPP Solution 100%

void inorder(vector<int>& ino, TreeNode* root) {

 

    if(root == NULL) return;

 

    inorder(ino, root->left);

    ino.push_back(root->data);

    inorder(ino, root->right);

}

 

void postorder(vector<int>& post, TreeNode* root) {

 

    if(root == NULL) return;

 

    postorder(post, root->left);

    postorder(post, root->right);

    post.push_back(root->data);

}

 

void preorder(vector<int>& pre, TreeNode* root) {

 

    if(root == NULL) return;

 

    pre.push_back(root->data);

    preorder(pre, root->left);

    preorder(pre, root->right);

}

 

vector<vector<int>> getTreeTraversal(TreeNode *root){

    // Write your code here.

 

    vector<int> ino, pre, post;

    inorder(ino, root);

    postorder(post, root);

    preorder(pre, root);

 

    vector<vector<int>> ans;

    ans.push_back(ino);

    ans.push_back(pre);

    ans.push_back(post);

 

    return ans;

}

457 views
0 replies
0 upvotes

Interview problems

MOST EASIEST AND OPTIMAL SOLUTION

/*

    Following is Binary Tree Node structure:

    class TreeNode

    {

    public:

        int data;

        TreeNode *left, *right;

        TreeNode() : data(0), left(NULL), right(NULL) {}

        TreeNode(int x) : data(x), left(NULL), right(NULL) {}

        TreeNode(int x, TreeNode *left, TreeNode *right) : data(x), left(left), right(right) {}

    };

*/

vector<vector<int>> getTreeTraversal(TreeNode *root){

    stack<pair<TreeNode*,int>>st;

    st.push({root,1});

    vector<int>inorder,pre,post;

    if(root==NULL) return {};

    while(!st.empty()){

        auto it = st.top();

        st.pop();

 

        //preorder part

        if(it.second==1){

            pre.push_back(it.first->data);

            it.second++;

            st.push(it);

 

            if (it.first->left != NULL) {

            st.push({it.first->left,1});

        }

 

        }

 

    // inorder part

 

        else if(it.second==2){

            inorder.push_back(it.first->data);

            it.second++;

            st.push(it);

            if(it.first->right!=NULL){

                st.push({it.first->right,1});

            }

 

        }

 

        //postorder

 

        else{

            post.push_back(it.first->data); 

         }

 

    }

    vector<vector<int>>result;

    result.push_back(inorder);

    result.push_back(pre);

    result.push_back(post);

    return result;

}

350 views
0 replies
1 upvote

Interview problems

All tests passed with C++ SOLUTION


void inorder(vector<int>& ino, TreeNode* root) {

    if(root == NULL) return;

    inorder(ino, root->left);
    ino.push_back(root->data);
    inorder(ino, root->right);
}

void postorder(vector<int>& post, TreeNode* root) {

    if(root == NULL) return;

    postorder(post, root->left);
    postorder(post, root->right);
    post.push_back(root->data);
}

void preorder(vector<int>& pre, TreeNode* root) {

    if(root == NULL) return;

    pre.push_back(root->data);
    preorder(pre, root->left);
    preorder(pre, root->right);
}

vector<vector<int>> getTreeTraversal(TreeNode *root){
    // Write your code here.

    vector<int> ino, pre, post;
    inorder(ino, root);
    postorder(post, root);
    preorder(pre, root);

    vector<vector<int>> ans;
    ans.push_back(ino);
    ans.push_back(pre);
    ans.push_back(post);

    return ans;
}
613 views
0 replies
0 upvotes

Interview problems

JAVA | Non Recursive | Using Pair Class

import java.util.*;
public class Solution {
    public static List<List<Integer>> getTreeTraversal(TreeNode root) {
        // Write your code here.
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> pre = new ArrayList<>();
        List<Integer> in = new ArrayList<>();
        List<Integer> post = new ArrayList<>();

        Stack<Pair> st = new Stack<>();
        st.push(new Pair(root, 1));

        while(st.size() > 0){
            Pair top = st.peek();
            if(top.state == 1){
                pre.add(top.node.data);
                top.state++;
                if(top.node.left != null)
                    st.push(new Pair(top.node.left, 1));
            }else if(top.state == 2){
                in.add(top.node.data);
                top.state++;
                if(top.node.right != null)
                    st.push(new Pair(top.node.right, 1));
            }else{
                post.add(top.node.data);
                st.pop();
            }
        }

        res.add(in);
        res.add(pre);
        res.add(post);
        
        return res;
    }

    static class Pair{
        TreeNode node;
        int state;
        Pair(TreeNode node, int state){
            this.node = node;
            this.state = state;
        }
    }
}

java

312 views
0 replies
0 upvotes

Interview problems

C++ || Striver's || Iterative

vector<vector<int>> getTreeTraversal(TreeNode *root){

 

    if(!root) return {};

    

    vector<vector<int>> ans;

    vector<int> in, pre, post;

    stack<pair<TreeNode*, int>> st;

    st.push({root, 1});

 

    while(!st.empty()){

 

        TreeNode* node = st.top().first;

        int cnt = st.top().second;

        st.pop();

 

        if(cnt == 1){

            pre.push_back(node->data);

            st.push({node, cnt + 1});

            if(node->left) st.push({node->left, 1});

        }

 

        else if(cnt == 2){

            in.push_back(node->data);

            st.push({node, cnt + 1});

            if(node->right) st.push({node->right, 1});

        }

 

        else{

            post.push_back(node->data);

        }

 

    }

 

    ans.push_back(in);

    ans.push_back(pre);

    ans.push_back(post);

    

    return ans;

}

499 views
0 replies
2 upvotes

Interview problems

C++ Recursive || All in one traversal

void f(TreeNode* root, vector<vector<int>> &vec){
    if(root == NULL) return;
    vec[1].push_back(root->data);
    f(root->left, vec);
    vec[0].push_back(root->data);
    f(root->right, vec);
    vec[2].push_back(root->data);
}

vector<vector<int>> getTreeTraversal(TreeNode *root){
    vector<vector<int>> ans(3);
    f(root, ans);
    return ans;
}
317 views
0 replies
0 upvotes
Full screen
Console