A tree in JavaScript is a way to organize data in a hierarchy, with a main "root" and branches that lead to smaller "child" elements. It's like a family tree, where each person can have their own children.
- Each node has a parent and can have children, creating a hierarchy.
- We visit each node starting from the root using methods like depth-first or breadth-first.
JavaScript
class TreeNode {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
// Example: Creating a simple tree
let root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
console.log(root);
OutputTreeNode {
value: 1,
left: TreeNode { value: 2, left: null, right: null },
right: TreeNode { value: 3, left: null, right: null }
}
In this example
- The TreeNode class creates a node with a value and two child nodes (left and right), both initially set to null.
- A root node with value 1 is created, with its left child as 2 and right child as 3.
- console.log(root); prints the tree structure, showing the root node and its children.
How a tree works
- The starting point of the tree is the main parent node.
- Each node (branch) leads to smaller points called "children."
- Each child can have its own children, creating a hierarchy.
- The tree structure organizes data in layers, with each level representing a different generation or category.
- Data is accessed by visiting nodes starting from the root, either through depth-first or breadth-first methods.
- The structure makes it easy to add, remove, or search for data, especially in situations like file systems or hierarchical data management.
Components of a tree
1. Node
The numerical values that we write in a tree constitute the node of a tree.
10
/ \
2 5
In the above visual, all the numerical values that have been written in the tree like 10,2 and 5 are called as nodes of a tree.
2. Root
The topmost node of a tree that has no children is called as the root of the tree.
10
/ \
2 5
In the above visual representation 10 is the topmost node in the tree and there is no parent to the tree so 10 will be the root of this particular tree.
3. Edge
The connection between the two nodes is called as an edge in the binary tree.
10
/ \
2 5
In the above visual representation the '\' and the '/' lines are the edges for the above tree.
4. Parent Node
A node that has one or more child is called as the parent node for the corresponding child nodes that are connected to that node.
10
/ \
2 5
/\ /\
1 3 8 9
In the above visual all the nodes like 10,2,5 those are having one or more children are called as parent Nodes.
5. Child Node
All the nodes that are connected to a parent node are called as the child node to that parent node.
10
/ \
2 5
/\ /\
1 3 8 9
In the above visual all the nodes like 2, 5 ,1,3,8,9 that are connected to any parent node are called as the child nodes.
6. Leaf Node
A node that has no children or child nodes are called as the leaf nodes.
10
/ \
2 5
In the above visual representation the nodes 2 and 5 do not have any child nodes and these nodes are called as the leaf nodes.
7. Subtree
A tree formed by a parent node kept as a root and all its child nodes is called as a subtree.
10
/ \
2 5 ------> 2 (subtree1) 5 (subtree2)
/\ /\ /\ /\
1 3 8 9 1 3 8 9
In the above visual 2 and 5 are the parent nodes and 1,3 are the child to the parent node 2 so it will form a separate subtree and the
parent node 5 has two children 8 and 9 so it also forms a separate subtree
8. Depth
The number of edges in the path from the root to that specific node is called as the depth of that tree.
10
/ \
2 5
/\ /\
1 3 8 9
In the above visual 10 is a root node and 1,3,8,9 are leaf nodes. The edges kept in the path from the root node to the leaf node like in this case the edges between 10 and 1 is 2 so the depth of the node 1 will be 2
9. Height
The number of edges between a node and the farthest leaf to it is called as the height of the node.
10
/ \
2 5
/\ /\
1 3 8 9
In this case if a person want to find the height of node 2 then in that case number of edges from 2 to 1 which is the farthest leaf from 2 is will be taken as the height for node 2 which will be 1 in that case
10. Level
The level of a node is always depth+1 for that particular node.
10
/ \
2 5
/\ /\
1 3 8 9
In the above visual the level of node 2 is 2 as the edge between it and the root node is 1 and the level is depth+1n for a node
Implementation of a Tree
In this code we will create and print a binary tree in a simple way using JavaScript. It defines a Node class for the tree's nodes and a Trees class to build and display the tree structure. Here's a quick explanation of how it works.
JavaScript
class Node{
constructor(key)
{
this.key=key
this.left=null
this.right=null
}
}
class Trees{
static printTree(node,prefix="",isLeft)
{
if(node===null)
{
return
}
console.log(prefix+(isLeft?'|-':'|_')+node.key)
let newprefix=prefix+(isLeft?'| ':' ')
Trees.printTree(node.left,newprefix,true)
Trees.printTree(node.right,newprefix,false)
}
static tree()
{
let root=null
root=new Node(10)
root.left=new Node(5)
root.right=new Node(15)
root.left.left=new Node(2)
root.left.right=new Node(7)
root.right.left=new Node(2)
root.right.right=new Node(9)
Trees.printTree(root)
}
}
Trees.tree()
Output|_10
|-5
| |-2
| |_7
|_15
|-2
|_9
- The Node class creates a node with a value (key) and two child nodes (left and right), which start as null.
- The tree method builds a simple binary tree. The root node has the value 10, and it has left and right children with values 5 and 15, respectively. More nodes are added to form the tree structure.
- The printTree method is used to print the tree in a visual format. It shows the tree's structure with symbols like |- for left children and |_ for right children.
- The printTree method works recursively. It prints the current node and then calls itself for the left and right children, creating a tree-like structure in the console.
- Calling Trees.tree() creates the tree and prints it in the console, showing a clear visual representation of the tree's layout.
Coding Problems on tree
Advantages of Tree
- Efficient Data Organization: Trees help organize data hierarchically, making it easier to represent relationships, such as parent-child or nested structures.
- Faster Search Operations: Trees, especially binary search trees, allow faster search operations, reducing time complexity compared to linear search.
- Flexible Structure: Trees can easily grow or shrink by adding or removing nodes, making them dynamic and adaptable to changing data.
- Optimal for Hierarchical Data: Trees are ideal for representing hierarchical data like file systems, organization charts, or family trees.
- Efficient Sorting and Traversal: Trees enable efficient sorting, and traversal methods like in-order, pre-order, and post-order make it easier to access or manipulate data.
Types of trees
Conclusion
In conclusion, trees in JavaScript provide an efficient way to represent hierarchical data structures, allowing for easy traversal, insertion, and deletion of nodes. Whether it's a simple binary tree, a self-balancing tree like AVL or Red-Black Tree, or more specialized structures like heaps or tries, each type of tree offers unique advantages for various applications.
Similar Reads
What is JavaScript? JavaScript is a powerful and flexible programming language for the web that is widely used to make websites interactive and dynamic. JavaScript can also able to change or update HTML and CSS dynamically. JavaScript can also run on servers using tools like Node.js, allowing developers to build entire
6 min read
Binary Search Tree in Javascript In this article, we would be implementing the Binary Search Tree data structure in Javascript. A tree is a collection of nodes connected by some edges. A tree is a non linear data structure. A Binary Search tree is a binary tree in which nodes that have lesser value are stored on the left while the
9 min read
Inverting a Binary Tree in JavaScript One can Invert a binary tree using JavaScript. Inverting a binary tree, also known as mirroring a binary tree, is the process of swapping the left and right children of all nodes in the tree. Below is the diagram to understand the problem clearlyInverting a binary treeBelow are the approaches to inv
5 min read
Build Tree Array from JSON in JavaScript Building a tree array from JSON in JavaScript involves converting a JSON object representing a hierarchical structure into an array that reflects the parent-child relationships. This tree array can be useful for various purposes like rendering hierarchical data in UI components performing tree-based
3 min read
JavaScript Trees Coding Practice Problems Trees are an essential data structure used to represent hierarchical data. They are particularly useful for applications involving searching, sorting, and decision-making processes. This curated list of JavaScript Tree Coding Practice Problems will help you master tree operations. Whether you're a b
2 min read
Self Balancing BST in JavaScript A self-balancing binary search tree (BST) is a type of binary search tree that automatically keeps its height balanced in order to guarantee that operations such as searching, inserting, and deleting elements in the tree take less time on average. How do self-balancing BSTs maintain height balance?
11 min read
JavaScript Data Structures Quizzes This quiz is designed to test your understanding of JavaScript's data structures, such as Numbers, Strings, Arrays, Linked Lists, Stacks, and Queues. By practicing, youâll reinforce your knowledge and gain confidence in identifying, using, and implementing these data structures in JavaScript.Data St
1 min read
Check Symmetrical Binary Tree using JavaScript Given a binary tree, our task is to check whether it is Symmetrical Binary tree. In other words, we need to check whether the binary tree is a mirror of itself. Example: Input: 11 / \ 12 12 / \ / \ 13 14 14 13Output: True Input: 11 / \ 12 12 \ \ 13 13Output: FalseBelow are the approaches to check Sy
3 min read
Build Tree Array from Flat Array in JavaScript To convert a flat array of comments into a tree-like structure using JavaScript. This technique is particularly useful when you need to render nested comments or any other hierarchical data in your web application. We will write a function called buildCommentsTree that takes the flat array of commen
7 min read
Boundary Traversal of Binary Tree using JavaScript The Boundary Traversal of the Binary Tree can be done by traversing the left, right, and leaf parts of the Binary Tree. We will break the Boundary Traversal of Binary Tree using JavaScript in three parts. First, we will traverse the left part, right part, and leaf parts of the Binary Tree and print
4 min read