Function to find the minimum depth of a tree
This code will visit every node in the tree, but it's not always necessary to do all that work. Instead you can do a breadth-first traversal of the tree, and look for the first node that has no children.

Consider this tree:

    o
   / \
  o   o
       \
        o
         \
          o
          ...
            o
             \
              o


With a breadth-first traversal, you only need to look at two nodes to determine the minimum depth. With the current code, you will visit every node and use \$O(n)\$ stack space in the process.

In some cases you will have to traverse every node, but my point is that sometimes you can do better.

The only trick is that you also have to keep track of the depth of each node.

The idea is to:


Enqueue the root onto a queue
While the queue is not empty:


Dequeue from the queue
If the node has no children, return its depth; this is a node of minimum depth in the tree.
Otherwise, enqueue the children of the node onto the queue