height of a tree

I want to know the ways to find out height (or depth) of a tree. Please suggest some ideas. I have an idea of bread-first-search algorithm. But I'm sure it could be done in more than one way. Could it be done by Depth-first-search, recursion or any other method?

Please note that the tree is not necessarily a binary search tree.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int MyTree::GetDepth()
{
  int depth = 0;
  int maxdepth = 0;

  FindDepth(top_node,depth,maxdepth);

  return maxdepth;
}

void MyTree::FindDepth(Node* top_node,int& depth,int& maxdepth)
{
  ++depth;
  if(depth > maxdepth)
    maxdepth = depth;

  for( .. each child node .. )
    FindDepth( the_child_node, depth,maxdepth );

  --depth;
}
Here if I don't pass the arguments by reference in the recursive function call - "depth" and instead pass the arguments by value, then the only difference in the program would be, I would not need to decrement "depth", since the "versions" of depth object would be saved in the stack and corresponding versions would be invoked during the stack unwinding. Is that correct?

If it is correct, then what is the distinct advantage of using reference arguments over non reference arguments? Or is there any?

Thanks.
I think it should be
1
2
3
4
5
6
7
8
9
10
11
12
13
14
int tree::getTreeDepth(){
    return root->treeDepth();
}

int treeNode::treeDepth(){
    int max=0;
    for each branch{
        int depth=branch->treeDepth();
        if (depth>max)
            max=depth;
    }
    //Add one to count self.
    return max+1;
}
Last edited on
Topic archived. No new replies allowed.