What will be the time and space complexity for vertical order traversal of a binary tree?

I have written the following c++ function to traverse a binary tree in vertical order. For nodes on the same vertical level, I want to store them in the order they will appear in the level order traversal.

Example: If we have the tree like this:

    1
  /   \
 2     3
/ \   /  \
4  5 6   7

I want to return a vector of vectors as:

{
{4}
{2}
{1 5 6}
{3}
{7}
}
void traversal(TreeNode* node, int x, int y, map<int,map<int,vector<int>>> &m){
    if(node == NULL){
        return;
    }
    if(m[x].find(y) == m[x].end()){
        vector<int> temp;
        m[x][y] = temp;
    }
    m[x][y].push_back(node->val);
    traversal(node->left,x-1,y+1,m);
    traversal(node->right,x+1,y+1,m);
    return;
    
} 
vector<vector<int>> verticalOrderTraversal(TreeNode* A) {
    map<int,map<int,vector<int>>> m;
    traversal(A,0,0,m);
    vector<vector<int>> ans;
    for(auto itr:m){
        vector<int> temp;
        for(auto itr2:itr.second){
            for(auto i:itr2.second){
                temp.push_back(i);
            }
        }
        ans.push_back(temp);
    }
    return ans;
}

How do I calculate its time complexity and space complexity in big O notation?

I read somewhere that the optimized code is of O(NlogN) time complexity. But it uses level order traversal. How do I calculate time complexity for my code that uses pre-order traversal?



Comments

Popular posts from this blog

Today Walkin 14th-Sept

Spring Elasticsearch Operations

Hibernate Search - Elasticsearch with JSON manipulation