Estructuras de datos 101: árbol de búsqueda binaria

Cómo combinar la eficiencia de la inserción de una lista vinculada y la búsqueda rápida de una matriz ordenada.

¿Qué es un árbol de búsqueda binaria?

Comencemos con la terminología básica para que podamos compartir el mismo idioma e investigar conceptos relacionados. Primero, ¿cuáles son los principios que definen un árbol de búsqueda binario?

* De ahora en adelante usaré "BST" por brevedad.

Un BST se considera una estructura de datos formada por nodos , como Listas vinculadas . Estos nodos son nulos o tienen referencias (enlaces) a otros nodos. Estos "otros" nodos son nodos secundarios, llamados nodo izquierdo y nodo derecho. Los nodos tienen valores . Estos valores determinan dónde se colocan dentro de la BST.

De manera similar a una lista vinculada, cada nodo es referenciado solo por otro nodo, su padre (excepto por el nodo raíz). Entonces podemos decir que cada nodo en una BST es en sí misma una BST. Porque más abajo en el árbol, llegamos a otro nodo y ese nodo tiene una izquierda y una derecha. Luego, dependiendo de hacia dónde vayamos, ese nodo tiene una izquierda y una derecha y así sucesivamente.

1. El nodo izquierdo siempre es más pequeño que su padre.

2. El nodo derecho es siempre mayor que su padre.

3. Un BST se considera equilibrado si todos los niveles del árbol están completamente llenos con la excepción del último nivel. En el último nivel, el árbol se llena de izquierda a derecha.

4. Un BST perfecto es aquel en el que está completo y completo (todos los nodos secundarios están en el mismo nivel y cada nodo tiene un nodo secundario izquierdo y uno derecho).

¿Por qué usaríamos esto?

¿Cuáles son algunos ejemplos del mundo real de BST? Los árboles se utilizan a menudo en búsquedas, lógica de juegos, tareas de autocompletar y gráficos.

Velocidad. Como se mencionó anteriormente, la BST es una estructura de datos ordenada. Tras la inserción, los nodos se colocan de forma ordenada. Este orden inherente hace que la búsqueda sea rápida. De manera similar a la búsqueda binaria (con una matriz que está ordenada), cortamos la cantidad de datos para clasificar a la mitad en cada pasada. Por ejemplo, supongamos que buscamos un valor de nodo pequeño. En cada pasada, seguimos moviéndonos a lo largo del nodo más a la izquierda. ¡Esto elimina la mitad de los valores mayores automáticamente!

Además, a diferencia de una matriz, los datos se almacenan por referencia. A medida que agregamos a la estructura de datos, creamos un nuevo bloque en la memoria y lo vinculamos. Esto es más rápido que crear una nueva matriz con más espacio y luego insertar los datos de la matriz más pequeña en la nueva y más grande.

En resumen, insertar, eliminar y buscar son las estrellas de un BST

Ahora que entendemos los principios, los beneficios y los componentes básicos de un BST, implementemos uno en javascript.

La API para una BST consta de lo siguiente: Insertar, Contiene, Obtener mínimo, Obtener máximo, Eliminar nodo, Verificar si está completo, está equilibrado y los tipos de búsqueda: profundidad primero (preorder, inOrder, postOrder), amplitud primero búsqueda , y por último Get Height . Esa es una gran API, solo tómala una sección a la vez.

Implementación

El constructor

La BST está formada por nodos y cada nodo tiene un valor.

function Node(value){ this.value = value; this.left = null; this.right = null;}

El constructor BST se compone de un nodo raíz.

function BinarySearchTree() { this.root = null;}
let bst = new BST();let node = new Node();
console.log(node, bst); // Node { value: undefined, left: null, right: null } BST { root: null }

… Hasta aquí todo bien.

Inserción

BinarySearchTree.prototype.insert = function(value){ let node = new Node(value); if(!this.root) this.root = node; else{ let current = this.root; while(!!current){ if(node.value  current.value){ if(!current.right){ current.right = node; break; } current = current.right; } else { break; } } } return this; };
let bst = new BST();bst.insert(25); // BST { root: Node { value: 25, left: null, right: null } }

Agreguemos algunos valores más.

bst.insert(40).insert(20).insert(9).insert(32).insert(15).insert(8).insert(27);
BST { root: Node { value: 25, left: Node { value: 20, left: [Object], right: null }, right: Node { value: 40, left: [Object], right: null } } }

Para una visualización genial ¡¡Vaya aquí !!

Desempaquetemos esto.

  1. Primero, pasamos un valor y creamos un nuevo nodo
  2. Verifique si hay una raíz, si no, configure este nodo recién creado en el nodo raíz
  3. Si hay un nodo raíz, creamos una variable declarada "actual" y establecemos su valor en el nodo raíz.
  4. Si el node.value recién creado es menor que el nodo raíz, nos moveremos a la izquierda
  5. Seguimos comparando este node.value con los nodos izquierdos.
  6. Si el valor es lo suficientemente pequeño y llegamos a un punto donde ya no quedan nodos, colocamos este elemento aquí.
  7. Si el valor de node.value es mayor, repetimos los mismos pasos que el anterior, excepto que nos movemos por la derecha.
  8. Necesitamos las declaraciones de interrupción porque no hay un paso de conteo para terminar el ciclo while.

Contiene

Este es un enfoque bastante sencillo.

BinarySearchTree.prototype.contains = function(value){ let current = this.root; while(current){ if(value === current.value) return true; if(value  current.value) current = current.right; } return false;};

Obtenga Min y Obtenga Max.

Siga desplazándose hacia la izquierda hasta el valor más pequeño o hacia la derecha para el más grande.

BinarySearchTree.prototype.getMin = function(node){ if(!node) node = this.root; while(node.left) { node = node.left; } return node.value};
BinarySearchTree.prototype.getMax = function(node){ if(!node) node = this.root; while(node.right) { node = node.right; } return node.value;};

Eliminación

Removing a node is the trickiest operation, because nodes have to be reordered to maintain the properties of a BST. There is a case if a node has only one child and a case if there is both a left and a right node. We use the larger helper function to do the heavy lifting.

BinarySearchTree.prototype.removeNode = function(node, value){ if(!node){ return null; } if(value === node.value){ // no children if(!node.left && !node.right) return null; // one child and it’s the right if(!node.left) node.right;// one child and it’s the left if(!node.right) node.left; // two kids const temp = this.getMin(node.right); node.value = temp; node.right = this.removeNode(node.right, temp); return node; } else if(value < node.value) { node.left = this.removeNode(node.left, value); return node; } else { node.right = this.removeNode(node.right, value); return node; }};
BinarySearchTree.prototype.remove = function(value){ this.root = this.removeNode(this.root, value);};

It works like this…

Unlike deleteMin and deleteMax, where we can just traverse all the way left or all the way right and pick off the last value, we have to take out a node and then replace it with something. This solution was developed in 1962 by T. Hibbard. We account for the case where we can delete a node with only one child or none, that’s minor. If no children, no problem. If a child is present, that child just moves up one.

But with a node scheduled to be removed that has two children, which child takes its place? Certainly, we can’t move a larger node down. So what we do is replace it with its successor, the next kingpin. We have to find the smallest right child on the right that is larger than the left child.

  1. Create a temp value and store the smallest node on its right. What this does is satisfy the property that values to the left are still smaller and values to the right are still greater.
  2. Reset the node’s value to this temp variable
  3. Remove the right node.
  4. Then we compare values on the left and the right and determine the assigned value.

This is best explained with a picture:

Searching

There are two types of search, Depth First and Breadth First. Breadth First is simply stopping at each level on the way down. It looks like this: we start at the root, then the left child, then the right child. Move to the next level, left child then right child. Think of this as moving horizontally. We employ, I should say simulate, a queue to help order the process. We pass a function, because many times we want to operate on a value.

BinarySearchTree.prototype.traverseBreadthFirst = function(fn) { let queue = []; queue.push(this.root); while(!!queue.length) { let node = queue.shift(); fn(node); node.left && queue.push(node.left); node.right && queue.push(node.right); }}

Depth First Search involves moving down the BST in a specified manner, either, preOrder, inOrder, or postOrder. I’ll explain the differences shortly.

In the spirit of concise code, we have a basic traverseDepthFirst function and we pass a function and a method. Again the function implies that we want to do something to the values along the way, while the method is the type of search we wish to perform. In the traverseDFS, we have a fallback: preOrder search in place.

Now, how is each one different? First, let’s dispatch inOrder. It should be self-explanatory but it isn’t. Do we mean in order of insertion, in order of highest to lowest or lowest to highest? I just wanted you to consider these things beforehand. In this case, yes, it does mean lowest to highest.

preOrder can be thought of as Parent, Left Child, then Right child.

postOrder as Left Child, Right Child, Parent.

BinarySearchTree.prototype.traverseDFS = function(fn, method){ let current = this.root; if(!!method) this[method](current, fn); else this._preOrder(current, fn);};
BinarySearchTree.prototype._inOrder = function(node, fn){ if(!!node){ this._inOrder(node.left, fn); if(!!fn) fn(node); this._inOrder(node.right, fn); }};
BinarySearchTree.prototype._preOrder = function(node, fn){ if(node){ if(fn) fn(node); this._preOrder(node.left, fn); this._preOrder(node.right, fn); }};
BinarySearchTree.prototype._postOrder = function(node, fn){ if(!!node){ this._postOrder(node.left, fn); this._postOrder(node.right, fn); if(!!fn) fn(node); }};

Check if the BST is full

Remember from earlier, a BST is full if every node has Zero or Two children.

// a BST is full if every node has zero two children (no nodes have one child)
BinarySearchTree.prototype.checkIfFull = function(fn){ let result = true; this.traverseBFS = (node) => { if(!node.left && !node.right) result = false; else if(node.left && !node.right) result = false; } return result;};

Get Height of BST

What does it mean to get the height of a tree? Why is this important? This is where Time Complexity (aka Big O) comes into play. Basic operations are proportional to the height of a tree. So as we alluded to earlier, if we search for a particular value, the number of operations we have to do is halved on each step.

That means if we have a loaf of bread and cut it in half, then cut that half in half, and keep doing that till we get the exact piece of bread we want.

In computer science, this is called O(log n). We start with an input size of some sort, and over time that size gets smaller (kind of flattening out). A straight linear search is denoted as O(n), as the input size increases so does the time it takes to run operations. O(n) conceptually is a 45-degree line starting at origin zero on a chart and moving right. The horizontal scale represents the size of an input and the vertical scale represents the time it takes to complete.

Constant time is O(1). No matter how large or small the input size is, the operation takes place in the same amount of time. For example, push() and pop() off of an array are constant time. Looking up a value in a HashTable is constant time.

I will explain more about this in a future article, but I wanted to arm you with this knowledge for now.

Back to height.

We have a recursive function, and our base case is: ‘if we have no node then we start at this.root’. This implies that we can start at values lower in the tree and get tree sub-heights.

So if we pass in this.root to start, we recursively move down the tree and add the function calls to the execution stack (other articles here). When we get to the bottom, the stack is filled. Then the calls get executed and we compare the heights of the left and the heights of the right and increment by one.

BinarySearchTree.prototype._getHeights = function(node){ if(!node) return -1; let left = this._getHeights(node.left); let right = this._getHeights(node.right); return Math.max(left, right) + 1;};
BinarySearchTree.prototype.getHeight = function(node){ if(!node) node = this.root; return this._getHeights(node);};

Lastly, Is Balanced

What we are doing is checking if the tree is filled at every level, and on the last level, if it is filled left to right.

BinarySearchTree.prototype._isBalanced = function(node){ if(!node) return true; let heightLeft = this._getHeights(node.left); let heightRight = this._getHeights(node.right); let diff = Math.abs(heightLeft — heightRight); if(diff > 1) return false; else return this._isBalanced(node.left) && this._isBalanced(node.right);};
BinarySearchTree.prototype.isBalanced = function(node){ if(!node) node = this.root; return this._isBalanced(node);};

Print

Use this to visualize all the methods you see, especially depth first and breadth first traversals.

BinarySearchTree.prototype.print = function() { if(!this.root) { return console.log(‘No root node found’); } let newline = new Node(‘|’); let queue = [this.root, newline]; let string = ‘’; while(queue.length) { let node = queue.shift(); string += node.value.toString() + ‘ ‘; if(node === newline && queue.length) queue.push(newline); if(node.left) queue.push(node.left); if(node.right) queue.push(node.right); } console.log(string.slice(0, -2).trim());};

Our Friend Console.log!! Play around and experiment.

const binarySearchTree = new BinarySearchTree();binarySearchTree.insert(5);binarySearchTree.insert(3);
binarySearchTree.insert(7);binarySearchTree.insert(2);binarySearchTree.insert(4);binarySearchTree.insert(4);binarySearchTree.insert(6);binarySearchTree.insert(8);binarySearchTree.print(); // => 5 | 3 7 | 2 4 6 8
binarySearchTree.contains(4);
//binarySearchTree.printByLevel(); // => 5 \n 3 7 \n 2 4 6 8console.log('--- DFS inOrder');
binarySearchTree.traverseDFS(function(node) { console.log(node.value); }, '_inOrder'); // => 2 3 4 5 6 7 8
console.log('--- DFS preOrder');
binarySearchTree.traverseDFS(function(node) { console.log(node.value); }, '_preOrder'); // => 5 3 2 4 7 6 8
console.log('--- DFS postOrder');
binarySearchTree.traverseDFS(function(node) { console.log(node.value); }, '_postOrder'); // => 2 4 3 6 8 7 5
console.log('--- BFS');
binarySearchTree.traverseBFS(function(node) { console.log(node.value); }); // => 5 3 7 2 4 6 8
console.log('min is 2:', binarySearchTree.getMin()); // => 2
console.log('max is 8:', binarySearchTree.getMax()); // => 8
console.log('tree contains 3 is true:', binarySearchTree.contains(3)); // => true
console.log('tree contains 9 is false:', binarySearchTree.contains(9)); // => false
// console.log('tree height is 2:', binarySearchTree.getHeight()); // => 2
console.log('tree is balanced is true:', binarySearchTree.isBalanced(),'line 220'); // => true
binarySearchTree. remove(11); // remove non existing node
binarySearchTree.print(); // => 5 | 3 7 | 2 4 6 8
binarySearchTree.remove(5); // remove 5, 6 goes up
binarySearchTree.print(); // => 6 | 3 7 | 2 4 8
console.log(binarySearchTree.checkIfFull(), 'should be true');
var fullBSTree = new BinarySearchTree(10);
fullBSTree.insert(5).insert(20).insert(15).insert(21).insert(16).insert(13);
console.log(fullBSTree.checkIfFull(), 'should be true');
binarySearchTree.remove(7); // remove 7, 8 goes up
binarySearchTree.print(); // => 6 | 3 8 | 2 4
binarySearchTree.remove(8); // remove 8, the tree becomes unbalanced
binarySearchTree.print(); // => 6 | 3 | 2 4
console.log('tree is balanced is false:', binarySearchTree.isBalanced()); // => true
console.log(binarySearchTree.getHeight(),'height is 2')
binarySearchTree.remove(4);
binarySearchTree.remove(2);
binarySearchTree.remove(3);
binarySearchTree.remove(6);
binarySearchTree.print(); // => 'No root node found'
//binarySearchTree.printByLevel(); // => 'No root node found'
console.log('tree height is -1:', binarySearchTree.getHeight()); // => -1
console.log('tree is balanced is true:', binarySearchTree.isBalanced()); // => true
console.log('---');
binarySearchTree.insert(10);
console.log('tree height is 0:', binarySearchTree.getHeight()); // => 0
console.log('tree is balanced is true:', binarySearchTree.isBalanced()); // => true
binarySearchTree.insert(6);
binarySearchTree.insert(14);
binarySearchTree.insert(4);
binarySearchTree.insert(8);
binarySearchTree.insert(12);
binarySearchTree.insert(16);
binarySearchTree.insert(3);
binarySearchTree.insert(5);
binarySearchTree.insert(7);
binarySearchTree.insert(9);
binarySearchTree.insert(11);
binarySearchTree.insert(13);
binarySearchTree.insert(15);
binarySearchTree.insert(17);
binarySearchTree.print(); // => 10 | 6 14 | 4 8 12 16 | 3 5 7 9 11 13 15 17
binarySearchTree.remove(10); // remove 10, 11 goes up
binarySearchTree.print(); // => 11 | 6 14 | 4 8 12 16 | 3 5 7 9 x 13 15 17
binarySearchTree.remove(12); // remove 12; 13 goes up
binarySearchTree.print(); // => 11 | 6 14 | 4 8 13 16 | 3 5 7 9 x x 15 17
console.log('tree is balanced is true:', binarySearchTree.isBalanced()); // => true
//console.log('tree is balanced optimized is true:', binarySearchTree.isBalancedOptimized()); // => true
binarySearchTree.remove(13); // remove 13, 13 has no children so nothing changes
binarySearchTree.print(); // => 11 | 6 14 | 4 8 x 16 | 3 5 7 9 x x 15 17
console.log('tree is balanced is false:', binarySearchTree.isBalanced()); // => false
// yields ...5 | 3 7 | 2 4 6 8--- DFS inOrder2345678--- DFS preOrder5324768--- DFS postOrder2436875--- BFS5372468min is 2: 2max is 8: 8tree contains 3 is true: truetree contains 9 is false: falsetree is balanced is true: true line 2205 | 3 7 | 2 4 6 86 | 3 7 | 2 4 8true 'should be true'true 'should be true'6 | 3 8 | 2 46 | 3 | 2 4tree is balanced is false: false2 'height is 2'No root node foundtree height is -1: -1tree is balanced is true: true---tree height is 0: 0tree is balanced is true: true10 | 6 14 | 4 8 12 16 | 3 5 7 9 11 13 15 1711 | 6 14 | 4 8 12 16 | 3 5 7 9 13 15 1711 | 6 14 | 4 8 13 16 | 3 5 7 9 15 17tree is balanced is true: true11 | 6 14 | 4 8 16 | 3 5 7 9 15 17tree is balanced is false: false

Time Complexity

1. Insertion O(log n)

2. Removal O(log n)

3. Search O(log n)

Wow, that is indeed a lot of information. I hope the explanations were as clear and as introductory as possible. Again, writing helps me solidify concepts and as Richard Feynman said, “When one person teaches, two learn.”

Resources

Probably the best resource for visualizing, definitely use it:

Data Structure Visualization

David Galles Computer Science University of San Franciscowww.cs.usfca.eduBinaryTreeVisualiser - Binary Search Tree

Site description herebtv.melezinek.czVisuAlgo - Binary Search Tree, AVL Tree

A Binary Search Tree (BST) is a binary tree in which each vertex has only up to 2 children that satisfies BST property…visualgo.netBig-O Algorithm Complexity Cheat Sheet (Know Thy Complexities!) @ericdrowell

Hi there! This webpage covers the space and time Big-O complexities of common algorithms used in Computer Science. When…www.bigocheatsheet.comAlgorithms, 4th Edition by Robert Sedgewick and Kevin Wayne

The textbook Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne surveys the most important algorithms and data…algs4.cs.princeton.eduBinary search tree - Wikipedia

In computer science, binary search trees ( BST), sometimes called ordered or sorted binary trees, are a particular type…en.wikipedia.org