(Assuming that what you want to get is height of the tree including node given as parameter)
For empty tree (node == null
) you will get depth of -1.
For tree with 1 node you will receive:
1 + max(-1, -1) = 0
and so on, returning 0
should fix the problem, but general idea is fine.
As for optimization... if only thing you know about this tree is that it's binary tree, then this is the best you can get without caching heights in nodes.
As for finding closest leaf you could use BFS algorithm to do it efficiently, because it will go and discover nodes horizontally, and then then you can stop when you discover 1st leaf.
BFS pseudocode:
nodes.enqueue( tuple(node, 1)) //enqueue node with height == 1
while(nodes.count > 0)
{
(node, h) = nodes.dequeue()
if (node.left == null && node.right == null) return h; //If it's first leaf we've found, return it's height.
//Enqueue our childs with their height
if (node.left != null)
nodes.enqueue(node.left, h+1);
if (node.right != null)
nodes.enqueue(node.right, h+1);
}