Created
October 18, 2021 00:43
-
-
Save damiancipolat/6881303723cee2ae14d89b948d8bb0e7 to your computer and use it in GitHub Desktop.
Cuenta hojas de un arbol binario
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Se espera que el resultado lo muestres en un console.log | |
const arbol = { | |
num: 25, | |
izq: { | |
num: 23, | |
izq: { | |
num: 10, | |
}, | |
der: { | |
num: 80, | |
}, | |
}, | |
der: { | |
num: 28, | |
izq: { | |
num: 25, | |
}, | |
der: { | |
num: 27, | |
}, | |
}, | |
}; | |
type THoja ={ | |
num:number, | |
izq?:THoja, | |
der?:THoja | |
}; | |
//Detecta si un nodo es una hoj.a | |
const esHoja=(nodo:THoja):boolean=>!(nodo.izq||nodo.der); | |
//Cuenta cantidad de hojas del arbol. | |
const contar =(arbol:THoja):number=>{ | |
//Si es hoja siempre retorno 1. | |
if (esHoja(arbol)) | |
return 1; | |
//Analizo ramas. | |
let hojasNum:number = 0; | |
if (arbol.izq) | |
hojasNum = hojasNum+contar(arbol.izq); | |
if (arbol.der) | |
hojasNum=hojasNum+contar(arbol.der); | |
return hojasNum; | |
} | |
console.log(contar(arbol)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment