HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

How can I build an undirected tree from an array of edges in JavaScript?

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
edgesjavascriptfromhowtreeundirectedcanbuildarray

Problem

It's no secret that I've been solving LeetCode problems for a little while now. A pretty common requirement for solving many of these problems is parsing an array of edges to build an undirected tree. It's a pretty straightforward task, but I thought it would be useful to share a simple implementation in JavaScript, one I find myself reusing over and over again.
@Quick refresher
Before we delve into the code, I'd like to note that, for a tree with n vertices, the number of edges is exactly n - 1. This is a fundamental property of trees, and it helps us ensure that we are indeed building a valid tree structure. It can also help us allocate memory, if we so desire.
> [!TIP]
>

Solution

const edges = [ [0, 1], [0, 2], [2, 3], [2, 4] ];


Before we delve into the code, I'd like to note that, for a tree with n vertices, the number of edges is exactly n - 1. This is a fundamental property of trees, and it helps us ensure that we are indeed building a valid tree structure. It can also help us allocate memory, if we so desire.
> [!TIP]
>
> This, in fact, is a very practical tip for traversing the tree in some cases, especially if you can skip building it altogether. If you're smart about it, you can increase performance like this and save up on memory, too!
Let's also have an example of an undirected tree, so we can visualize what we're building:
!Undirected Tree visualization

Code Snippets

const edges = [ [0, 1], [0, 2], [2, 3], [2, 4] ];
const edgesToChildGraph = edges =>
  edges.reduce((acc, [a, b]) => {
    if (!acc.has(a)) acc.set(a, []);
    if (!acc.has(b)) acc.set(b, []);
    acc.get(a).push(b);
    return acc;
  }, new Map());

edgesToChildGraph(edges);
// Map(0 => [1, 2], 1 => [], 2 => [3, 4], 3 => [], 4 => [])
const edgesToParentGraph = edges =>
  edges.reduce((acc, [a, b]) => {
    acc.set(b, a);
    return acc;
  }, new Map());

edgesToParentGraph(edges);
// Map(1 => 0, 2 => 0, 3 => 2, 4 => 2)

Context

From 30-seconds-of-code: undirected-tree-from-edges

Revisions (0)

No revisions yet.