How to create and use trees

To create a tree, you first need to create a node. A node is a piece of data that contains two parts: the data itself, and a list of child nodes.

var node = {
  data: "Root",
  children: []
};

Adding Children to a Tree

To add a child to a tree, you need to add the child node to the children list of the parent node.

node.children.push({
  data: "Child 1"
});

Traversing a Tree

To traverse a tree, you need to start at the root node and then follow the children list of each node until you reach the end of the tree.

var currentNode = node;
while (currentNode != null) {
  document.write(currentNode.data);
  currentNode = currentNode.children[0];
}

Examples in JavaScript

Trees can be used to represent the structure of a file system, family relationships, or websites.

Try to run code by using of Front-end Editor by clicking the button Try Our Frontend Editor (HTML/CSS/JS) below.