Trees
A tree is a hierarchical data structure that consists of nodes connected by edges. The first node in a tree is called the root, and the nodes below the root are called the children. Nodes with no children are called leaf nodes. Trees can be used to model hierarchical relationships, such as file systems, organizational charts, and HTML document object models.
Here is an example of creating a binary tree in JavaScript:
class Node {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
class BinaryTree {
constructor() {
this.root = null;
}
insert(value) {
const newNode = new Node(value);
if (!this.root) {
this.root = newNode;
return;
}
let currentNode = this.root;
while (true) {
if (value < currentNode.value) {
if (!currentNode.left) {
currentNode.left = newNode;
return;
}
currentNode = currentNode.left;
} else {
if (!currentNode.right) {
currentNode.right = newNode;
return;
}
currentNode = currentNode.right;
}
}
}
search(value) {
let currentNode = this.root;
while (currentNode) {
if (value === currentNode.value) {
return currentNode;
}
if (value < currentNode.value) {
currentNode = currentNode.left;
} else {
currentNode = currentNode.right;
}
}
return null;
}
}
In this example, the BinaryTree class is defined with several methods, including insert() and search(). The insert() method adds a new node with the given value to the tree in the appropriate position according to the value. The search() method searches the tree for a node with the given value and returns the node if found, or null otherwise.
The Node class represents a single node in the tree and has a value property to store the value of the node and leftand right properties to reference the left and right child nodes.
Here are some examples of how to use the BinaryTree class:
const tree = new BinaryTree();
tree.insert(5);
tree.insert(3);
tree.insert(7);
tree.insert(2);
tree.insert(4);
tree.insert(6);
tree.insert(8);
console.log(tree.search(4)); // Output: Node { value: 4, left: Node { value: 2, left: null, right: null }, right: Node { value: 5, left: [Node], right: [Node] } }
console.log(tree.search(9)); // Output: null
In this example, we create a new BinaryTree object and add several nodes to it using the insert() method. We then use the search() method to find a node with a specific value in the tree.
Trees can be used in a variety of applications, such as representing family trees, decision trees, and search trees.