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

190
Visualizações
Tratando de resolver el ancestro común más bajo

la pregunta se publica en la imagen de abajo

 var lowestCommonAncestor = function(root, p, q) { // return the path to the node let path = [] const search = (node, target) => { if (node === null) return false path.push(node) if (node === target) return true const leftSearched = search(node.left, target) if (leftSearched) return true const rightSearched = search(node.right,target) if (rightSearched) return true path.pop() } search(root, p) const pathP = path path = [] search(root, q) const pathQ = path let result while(pathP.length > 0 && pathQ.length > 0 && pathP[0] === pathQ[0]) { result = pathP[0] pathP.shift() pathQ.shift() } return result }; console.log(lowestCommonAncestor([3,5,1,6,2,0,8,null,null,7,4],5,1));

Recibo el siguiente mensaje de error const leftSearched = search(node.left, target) ^ TypeError: No se puede leer la propiedad 'izquierda' de indefinido

Alguien podría ayudarme a solucionar este problema

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Leet Code, como otros sitios de desafío de código, transformará la entrada de la matriz (en realidad, la entrada de texto con notación JSON) en una instancia de TreeNode , y la pasará como argumento a la función con su código de solución.

Cuando desee ejecutar la solución localmente, tendrá que encargarse de esta transformación usted mismo. Para ese propósito, podría utilizar la función fromList , específicamente para árboles binarios.

NB: tiene un error en su función de search . if (node === target) debería ser if (node.val === target) .

 // LeetCode template: function TreeNode(val) { this.val = val; this.left = this.right = null; } // Tool to convert array input to a tree: function fromList(values) { if (!values) return; let it = (function* () { for (let value of values) { yield value == null ? null : new TreeNode(value); } while (true) yield null; })(); let root = it.next().value; let nextlevel = [root]; while (nextlevel.length) { let level = nextlevel; nextlevel = []; for (let node of level) { if (node) { node.left = it.next().value; node.right = it.next().value; nextlevel.push(node.left, node.right); } } } return root; } // Your function var lowestCommonAncestor = function(root, p, q) { // return the path to the node let path = [] const search = (node, target) => { if (node === null) return false; path.push(node); if (node.val === target) return true; const leftSearched = search(node.left, target); if (leftSearched) return true; const rightSearched = search(node.right,target); if (rightSearched) return true; path.pop(); } search(root, p); const pathP = path; path = []; search(root, q); const pathQ = path; let result; while(pathP.length > 0 && pathQ.length > 0 && pathP[0] === pathQ[0]) { result = pathP[0]; pathP.shift(); pathQ.shift(); } return result; }; // Running your solution on some input let input = [3,5,1,6,2,0,8,null,null,7,4]; // Make the conversion that LeetCode would do let root = fromList(input); let lca = lowestCommonAncestor(root,5,1); // For your own purposes, just print the value of that node: console.log(lca.val); // 3

about 4 years ago · Juan Pablo Isaza 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