add
e deve aceitar um valor inteiro para adicionar à árvore. Tome cuidado para manter a invariante de uma árvore de pesquisa binária: o valor em cada filho da esquerda deve ser menor ou igual ao valor pai, e o valor em cada filho da direita deve ser maior ou igual ao valor pai. Aqui, vamos fazer com que nossa árvore não possa conter valores duplicados. Se tentarmos adicionar um valor que já existe, o método deve retornar null
. Caso contrário, se a adição for bem sucedida, undefined
deve ser retornado.
Dica: as árvores são estruturas de dados naturalmente recursivas! BinarySearchTree
existe.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() }; return (typeof test == "object")})(), "The BinarySearchTree
data structure exists.");'
- text: A árvore de pesquisa binária tem um método chamado add
.
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 add
.");'
- text: O método add adiciona elementos de acordo com as regras da árvore de pesquisa binária.
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: Adicionar um elemento que já existe retorna null
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 null
");'
```