3.4 KiB
3.4 KiB
id | title | challengeType | videoUrl | localeTitle |
---|---|---|---|---|
587d8257367417b2b2512c7b | Add a New Element to a Binary Search Tree | 1 | Agregar un nuevo elemento a un árbol de búsqueda binario |
Description
add
y debe aceptar un valor entero para agregarlo al árbol. Tenga cuidado de mantener el invariante de un árbol de búsqueda binario: el valor en cada elemento secundario izquierdo debe ser menor o igual que el valor principal, y el valor en cada elemento secundario derecho debe ser mayor o igual que el valor principal. Aquí, hagamos que nuestro árbol no pueda contener valores duplicados. Si intentamos agregar un valor que ya existe, el método debe devolver null
. De lo contrario, si la adición es exitosa, se debe devolver undefined
. Pista: ¡los árboles son naturalmente estructuras de datos recursivas! Instructions
Tests
tests:
- text: La estructura de datos <code>BinarySearchTree</code> existe.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() }; return (typeof test == "object")})(), "The <code>BinarySearchTree</code> data structure exists.");'
- text: El árbol de búsqueda binario tiene un método llamado <code>add</code> .
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; return (typeof test.add == "function")})(), "The binary search tree has a method called <code>add</code>.");'
- text: El método add agrega elementos de acuerdo con las reglas del árbol de búsqueda binario.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; if (typeof test.add !== "function") { return false; }; test.add(4); test.add(1); test.add(7); test.add(87); test.add(34); test.add(45); test.add(73); test.add(8); const expectedResult = [ 1, 4, 7, 8, 34, 45, 73, 87 ]; const result = test.inOrder(); return (expectedResult.toString() === result.toString()); })(), "The add method adds elements according to the binary search tree rules.");'
- text: Añadiendo un elemento que ya existe devuelve <code>null</code>
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; if (typeof test.add !== "function") { return false; }; test.add(4); return test.add(4) == null; })(), "Adding an element that already exists returns <code>null</code>");'
Challenge Seed
var displayTree = (tree) => console.log(JSON.stringify(tree, null, 2));
function Node(value) {
this.value = value;
this.left = null;
this.right = null;
}
function BinarySearchTree() {
this.root = null;
// change code below this line
// change code above this line
}
After Test
console.info('after the test');
Solution
// solution required