Imagine a simple tree with only 3 nodes, 1 root and 2 children
Node R
/ \
/ \
Node A Node B
The first call to depth takes Node R as it's argument.
Call 1) q
is not NULL
so depth()
is called for Node R left == Node A
Call 2) q
is not NULL
so depth()
is called for Node A left == NULL
Call 3) q
is NULL
so return 0;
Call 2) h1 = 0;
Now call for Node A right = NULL
Call 4) q
is NULL
so return 0;
Call 2) h1 = 0; h2 = 0; return max(0, 0) + 1
Call 1) h1 = 1;
Now call for Node R right = Node B
Call 5) q
is not NULL
so depth()
is called for Node B left == NULL
Call 6) q
is NULL
so return 0;
Call 5) h1 = 0;
Now call for Node B right = NULL
Call 7) q
is NULL
so return 0;
Call 5) h1 = 0; h2 = 0; return max(0, 0) + 1;
Call 1) h1 = 1; h2 = 1; return max(1, 1) + 1;
Returns 2.