Playground

General Tree

Create and manipulate hierarchical N-ary tree structured nodes visually.

General Tree

A hierarchical data structure where each node can have any number of children. Click on a node to inspect it, then use the separate add/delete controls below.

class TreeNode {
data: any;
children: TreeNode[];
}
Add
Parent
Delete
Set a label and add root to begin.
EMPTY TREEAdd a root node to begin
100%

INSERT

newNode = Node(value)
If tree is empty:
ROOT = newNode
Else:
Find parentNode by value
parentNode.children.push(newNode)
Return success

Console Output

NODES: 0
>Waiting for operations...

Want to see how the recursive code works?

Copy this code and paste it in the Recursion Tracer to visualize the call stack step-by-step.

OPEN TRACER
class TreeNode {
  constructor(val) {
    this.val = val;
    this.children = [];
  }
}

function buildTree(pairs) {
  const nodeMap = {};
  let root = null;
  for (const pair of pairs) {
    const [val, parent] = pair.split(":").map(s => s.trim());
    const node = nodeMap[val] || new TreeNode(val);
    nodeMap[val] = node;
    if (!parent && !root) {
      root = node;
    } else if (parent && nodeMap[parent]) {
      nodeMap[parent].children.push(node);
    }
  }
  return root;
}

function preorder(node) {
  if (!node) return [];
  let result = [node.val];
  for (const child of node.children) {
    result = result.concat(preorder(child));
  }
  return result;
}

// Build and traverse
const input = "A, B:A, C:A, D:B, E:B, F:C";
const pairs = input.split(",").map(s => s.trim());
const root = buildTree(pairs);
console.log("Preorder:", preorder(root));