Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this level order traversal run in O(n) time?

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

        queue<TreeNode*> bfs;
        if (root != nullptr) bfs.push(root);
        vector<vector<int>> sol;
        vector<TreeNode*> temp; 
        vector<int> indivSol;
        
        while (!bfs.empty()) {
            
            int currSz = bfs.size();
            for (int i = 0; i < currSz; i++) {
                temp.push_back(bfs.front());
                bfs.pop();
                
                indivSol.push_back(temp.at(i)->val);                

                if (temp.at(i)->left != nullptr) bfs.push(temp.at(i)->left);
                if (temp.at(i)->right != nullptr) bfs.push(temp.at(i)->right);
            }
            
            temp.clear();
            sol.push_back(indivSol);
            indivSol.clear();
            
        }
        
        return sol;
    }

I know that the outer while loop will run n times (n being the number of nodes in the tree), but will the inner for loop make the solution run in O(n^2) time? Since a tree has at most 2^n nodes at level n, currSz can grow for each iteration of the outer loop from 1 to 2 to 4 to 8 to 16 ...

EDIT: realized that the outer loop will only run l many times where l is the number of levels

like image 876
csguy Avatar asked Dec 18 '22 12:12

csguy


1 Answers

Forget everything, just recall that when you are performing level order traversal using this code, you visit every node once. So, if in total there are k nodes in the tree then the time complexity will be O(k).

h : height of the tree

The while loop runs h times and at every iteration (i.e at every level) it traverses over all the nodes present in that level. So similarly this goes for every iteration (level) which results in O(n) (n is total no of nodes)

like image 181
Sai Sreenivas Avatar answered Dec 30 '22 13:12

Sai Sreenivas