tree in javascript

One way to represent a tree in JavaScript is to use a recursive approach with objects and arrays. Each node in the tree can be represented by an object with properties for its value and children, where children is an array of objects representing the node's immediate descendants.

Here is an example of a simple implementation:

index.tsx
class TreeNode {
  constructor(value) {
    this.value = value;
    this.children = [];
  }

  addChild(node) {
    this.children.push(node);
  }
}

// create root node
const root = new TreeNode('A');

// add child nodes
const b = new TreeNode('B');
const c = new TreeNode('C');
const d = new TreeNode('D');

root.addChild(b);
root.addChild(c);
b.addChild(d);
360 chars
23 lines

This creates a tree with root node A and child nodes B and C. Node B also has a child node D.

You can traverse the tree using recursion, starting from the root node:

index.tsx
function traverse(node) {
  // do something with the current node's value
  console.log(node.value);

  // traverse each child node recursively
  for (let i = 0; i < node.children.length; i++) {
    traverse(node.children[i]);
  }
}

traverse(root); // output: A B D C
269 chars
12 lines

gistlibby LogSnag