Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

310
Visualizações
Obtenga el índice de cada raíz en el nivel sabio en la estructura de datos del árbol

Hola, estoy trabajando en la estructura de datos de árbol. Quiero saber si podemos obtener el índice de cada nodo en nivel. El siguiente diagrama representa cómo quiero el valor + índice. El nivel A o B representa el valor del nodo y el valor del índice representa el valor del índice

 Node | | | Level A -> 1 2 3 index value-> 0 1 2 | | | | | | | | | | | | Leve B-> 4 5 6 7 8 9 index value-> 0 1 2 3 4 5 ....// more level

¿Cómo podemos lograr el índice en cada nivel sabio? Estoy agregando mi lógica de cómo estoy agregando valor en cada nivel. ¿Podría alguien sugerir cómo puedo lograr esto?

 var baseNode: LevelIndex = LevelIndex() var defaultId = "1234" fun main() { val list = getUnSortedDataListForLevel() val tempHashMap: MutableMap<String, LevelIndex> = mutableMapOf() list.forEach { levelClass -> levelClass.levelA?.let { levelA -> val levelOneTempHashMapNode = tempHashMap["level_a${levelA}"] if (levelOneTempHashMapNode != null) { if (defaultId == levelClass.id && levelOneTempHashMapNode is LevelOne) { levelOneTempHashMapNode.defaultValue = true } return@let } val tempNode = LevelOne().apply { value = levelA if (defaultId == levelClass.id) { defaultValue = true } } baseNode.children.add(tempNode) tempHashMap["level_a${levelA}"] = tempNode } levelClass.levelB?.let { levelB -> val levelTwoTempHashMapNode = tempHashMap["level_a${levelClass.levelA}_level_b${levelB}"] if (levelTwoTempHashMapNode != null) { if (defaultId == levelClass.id && levelOneTempHashMapNode is LevelTwo) { levelTwoTempHashMapNode.defaultValue = true } return@let } val tempNode = LevelTwo().apply { value = levelB if (defaultId == levelClass.id) { defaultValue = true } } val parent = tempHashMap["level_a${levelClass.levelA}"] ?: baseNode parent.children.add(tempNode) tempHashMap["level_a${levelClass.levelA}_level_b${levelB}"] = tempNode } levelClass.levelC?.let { levelC -> val tempNode = LevelThree().apply { value = levelC if (defaultId == levelClass.id) { defaultValue = true } } val parent = tempHashMap["level_a${levelClass.levelA}_level_b${levelClass.levelB}"] ?: baseNode parent.children.add(tempNode) } } } open class LevelIndex( var value: String? = null, var children: MutableList<LevelIndex> = arrayListOf() ) class LevelOne : LevelIndex() { var defaultValue: Boolean? = false } class LevelTwo : LevelIndex() { var defaultValue: Boolean? = false } class LevelThree : LevelIndex() { var defaultValue: Boolean = false }

ACTUALIZAR

Quiero un valor de índice por nivel de raíz porque, tengo una identificación, quiero hacer coincidir esa combinación con esa identificación, si ese valor está presente, estoy almacenando ese valor b true y necesito encontrar ese valor de índice.

 Node | | | Level A -> 1 2 3 index value-> 0 1 2 default value-> false true false | | | | | | | | | | | | Leve B-> 4 5 6 7 8 9 index value-> 0 1 2 3 4 5 default value->false false true false false false ....// more level

Entonces, Nivel A, obtendré el índice 1 .

Para el nivel B obtendré el índice 2

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Crearía una lista para ordenar los nodos en cada nivel. Puede recopilarlos recursivamente de su árbol.

 val nodesByLevel = List(3) { mutableListOf<LevelIndex>() } fun collectNodes(parent: LevelIndex) { for (child in parent.children) { val listIndex = when (child) { is LevelOne -> 0 is LevelTwo -> 1 is LevelThree -> 2 // I made LevelIndex a sealed class. Otherwise you would need an else branch here. } nodesByLevel[listIndex] += child collectNodes(child) } } collectNodes(baseNode)

Ahora nodesByLevel contiene tres listas que contienen todos los nodos en cada capa en orden.

Si solo necesita los valores de cadena, puede cambiar esa mutableList para usar un tipo de cadena y usar += child.value ?: "" en su lugar, aunque haría que el value no admita valores NULL (¿entonces no necesita ?: "" ), porque ¿de qué sirve un nodo sin valor?

Editar , movería defaultValue a la clase principal para que no tenga que convertir los nodos para poder leerlo. Y lo voy a tratar como no anulable.

 sealed class LevelIndex( var value: String = "", val children: MutableList<LevelIndex> = arrayListOf() var isDefault: Boolean = false )

Luego, si desea hacer algo con los elementos en función de sus índices:

 for ((layerNumber, layerList) in nodesByLevel.withIndex()) { for((nodeIndexInLayer, node) in layerList) { val selectedIndexForThisLayer = TODO() //with layerNumber node.isDefault = nodeIndexInLayer == selectedIndexForThisLayer } }
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda