Nicholas
Nicholas

Reputation: 7501

Understanding the run time for a tree type data structure

I have a data structure that is a tree, where each parent can have unlimited number of children, and the max depth of the tree is 4. Each level is a different class.

My friend has written an algorithm to traverse this is made up of for loops, the psuedocode is below:

root = tree.root();
for (int i = 0; i < root.children_size(); i++)
    child1 = root.child(i);
    for(int j = 0; j < child1.children_size(); j++)
        child2 = child1.child(j);
        for(int k = 0; k < child2.children_size(); k++)
            child3 = child2.child(k);

He claims that because this has 3 for loops, the run time of this algorithm is O(n3). When I ask him what n is, he said is the number of for loops, which doesn't make sense, because n has to be a structure within this tree. I claim n is the number of overall nodes in the tree and the run time of this algorithm is O(n), because the run time will be O(root.children_size + child1.children_size + child2.children_size).

Is my assumption about the run time correct, O(n), or is my friends, O(n^3)?

Upvotes: 1

Views: 290

Answers (2)

Wayne Rooney
Wayne Rooney

Reputation: 1607

Yes you are right . You are actually employing depth first search,which visits each node exactly once (i.e. worst case of a dfs) , hence complexity is O(N) .As far as your friend is concerned, I cant understand what he denotes by n because the depth(that is the number of for loops) here is fixed .

Upvotes: 1

srbhkmr
srbhkmr

Reputation: 2104

You are right. visiting every node once will make it O(N), where N is the total no. of nodes in the tree.

Upvotes: 0

Related Questions