Trying to calculate depth, deepest, for binary tree

I'm trying to write something to determine the largest depth of a binary tree but far have only ended up with one thing that keep giving back the number of nodes in the tree, and another, below, that is always one more or less off. After hours of trying to adjust this I could really use some advice..
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
void findthedepth(nodeoftree<node>* root, int* depthtotal, int* depthcurrent){

        int left = 0, right = 0;

       if( root == nullptr ){
           *depthtotal = 0;
           *depthcurrent = 0;
           return;
       }

       findthedepth(root->rightp(), depthtotal, depthcurrent);
       right = *depthcurrent;

       *depthcurrent = 0;

       findthedepth(root->leftp(), depthtotal, depthcurrent);
       left = *depthcurrent;


       if (left > right){ 
           *depthtotal += left + 1;
       }
       else { 
           *depthtotal += right + 1;
       }


   }
Last edited on
do any of the recursive tree traversals that touch every node, and you count as you go down nodes, stop counting when you hit null children, ... you need a max of those depths, to find the deepest one, and the current depth, to track it as you go.

You are close, I think.
You're really over-thinking the problem!

1
2
int max_depth(Node const& n)
{ return n? 1 + std::max(max_depth(n.left), max_depth(n.right)): 0; }

Last edited on
@mbozzi: That's what I would have normally done but its a one piece of a large assignment that says I have to have those two int* arguments to the function, and I'm just lost as to incorporating them correctly. We have TAs to ask but communication there isn't the best and so far they've only gotten me more confused.
Last edited on
Topic archived. No new replies allowed.