i think the problem is way more Conceptual
Consider this case from leetcode ( naive solution fails on this one)
# Source - https://stackoverflow.com/q/72233959
# Diagram Copies for the post above
2
/ \
NULL 3
/ \
NULL 4
/ \
NULL 5
/ \
NULL 6
we misunderstood the Meaning of actual depth in this case according to problem statement on leetcode
"The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node."
Note: A leaf is a node with no children.
Now understand the explicit meaning leaf node its is a node which has 0 children and since our root node( see diagram) has one children ( right children node with value 3 so it is not a leaf node) and that is where confussion kickin in our naive code we usually do Base case like this
if not node : return 0;
we consider it as leaf node but it does not guartantee its a leaf node it just means if any childern left or right is NULL but actual parent node may have other children ( right or vice versa)
while doing this we are unaware of that fact that we call a node if both its parent.left && parent.right are null
so in order to correctly identify a node as leaf we must check both of it left and right pointer only then we say its a leaf node
if( ! root) return 0; // it check whether root node even exists
// then we check if its LEAF NODE
if( root->left== NULL && root->right==NULL) return 1; // LEAF NODE no children
// other wise we have a may case i whicj one child may be null but now its not a leaf node and we do not //stop recursion( DFS)
inr left_height = depth(root->left);
int right_height = depth(root->right);
// now we have depth of both
if( root->left==NULL) return 1+ right;
if(root->right == NULL) return 1+ left;
// if both children of root nodes exists take min
return min(left_height,right_height) +1;