Cómo mejorar mi solución Java para el problema ‘nodo de hoja izquierda más profundo en un árbol binario’

Desea 2 valores de retorno: la profundidad y el nodo. Sin embargo, solo puede devolver uno de ellos en Java. Por lo tanto, la mejor manera es crear una clase simple para contener los valores que desea almacenar. Luego, la función devuelve un objeto de esta clase.

De esta manera, el código se simplifica enormemente.

static class TreeNodeDepthPair {
TreeNode node = null;
int depth; TreeNodeDepthPair(TreeNode n, int d) {
node = n;
depth = d;
}
}
private static TreeNode find(TreeNode root) {
TreeNodeDepthPair result = FindDeepestLeftChild(root, 0);
return result != null ? result.node : null;
}
private static TreeNodeDepthPair FindDeepestLeftChild(TreeNode root, int depth) {
if(root == null)
return null;
TreeNodeDepthPair resLeft = FindDeepestLeftChild(root.left, 1 + depth);
TreeNodeDepthPair resRight = FindDeepestLeftChild(root.right, 1 + depth);
// Check if there is left child and it does not have left children.
if (resLeft == null && root.left != null)
resLeft = new TreeNodeDepthPair(root.left, depth+1);
if (resRight != null && (resLeft == null || resRight.depth > resLeft.depth))
return resRight;
return resLeft;
}

static class TreeNodeDepthPair {
TreeNode node = null;
int depth; TreeNodeDepthPair(TreeNode n, int d) {
node = n;
depth = d;
}
}
private static TreeNode find(TreeNode root) {
TreeNodeDepthPair result = FindDeepestLeftChild(root, 0);
return result != null ? result.node : null;
}
private static TreeNodeDepthPair FindDeepestLeftChild(TreeNode root, int depth) {
if(root == null)
return null;
TreeNodeDepthPair resLeft = FindDeepestLeftChild(root.left, 1 + depth);
TreeNodeDepthPair resRight = FindDeepestLeftChild(root.right, 1 + depth);
// Check if there is left child and it does not have left children.
if (resLeft == null && root.left != null)
resLeft = new TreeNodeDepthPair(root.left, depth+1);
if (resRight != null && (resLeft == null || resRight.depth > resLeft.depth))
return resRight;
return resLeft;
}