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;
}
- ¿Debería alguien que se aplica a un campo de arranque de desarrollo ya saber cómo escribir una función para sumar una matriz multidimensional?
- En la industria, ¿con qué frecuencia se usa el algoritmo de compresión Lempel-Ziv-Welch?
- ¿Podemos encontrar si la matriz no contiene un elemento mayoritario en un tiempo casi constante?
- Cómo demostrar que el algoritmo de búsqueda uniforme de costos siempre genera una ruta óptima
- ¿Cómo funciona el ciclo for de este algoritmo?
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;
}