Skip to content

Commit 585bdcc

Browse files
committed
feat: adding RootingTreeFromGraph algorithm.
1 parent cc1e1dc commit 585bdcc

File tree

2 files changed

+88
-0
lines changed

2 files changed

+88
-0
lines changed

Trees/RootingTreeFromGraph.js

+59
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
/*
2+
* Author: Denton Kunz
3+
* Tree rooting algorithm in Javascript
4+
* Takes in an undirected graph (adjacency matrix)
5+
* Follows pseudocode given at https://youtu.be/2FFq2_je7Lg?si=rIwT8UCYcaGhxH6h
6+
* Node class can be modified to include a data field
7+
*/
8+
9+
class Node {
10+
constructor(id, parent, children=[]){
11+
this.id = id
12+
this.parent = parent
13+
this.children = children
14+
}
15+
}
16+
17+
function rootTree(graph, rootId=0){
18+
19+
console.log(graph)
20+
21+
//the first node (root) should start with no parents/children
22+
const root = new Node(rootId, null)
23+
//recursively generate the rest of the tree
24+
return buildTree(graph, root, null)
25+
}
26+
27+
function buildTree(graph, node, parent){
28+
//let i represent the id of the child node
29+
for (let i = 0; i < graph[node.id].length; i++) {
30+
//skip until we find a child node
31+
if(graph[node.id][i]==0){
32+
// console.log("skipped 1")
33+
continue
34+
}
35+
36+
//if the child node is the current node, skip this case
37+
if(node.id == i){
38+
// console.log("skipped 2")
39+
continue
40+
}
41+
42+
//avoid creating an edge between child and the current node's parent
43+
if( parent != null && i == parent.id){
44+
// console.log("skipped 3")
45+
continue
46+
}
47+
48+
//create and add the new node
49+
let child = new Node(i, node)
50+
node.children.push(child)
51+
52+
//recursively iterate using that node
53+
buildTree(graph, child, node)
54+
}
55+
56+
return node
57+
}
58+
59+
export {Node, rootTree, buildTree}
+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import {rootTree} from '../RootingTreeFromGraph'
2+
3+
describe('Test 1', () =>{
4+
/* Graph structure:
5+
*
6+
* 0 3 - 4
7+
* \ /
8+
* 1
9+
* /
10+
* 2
11+
*/
12+
const myGraph = [[1,1,0,0,0],
13+
[1,1,1,1,0],
14+
[0,1,1,0,0],
15+
[0,1,0,1,1],
16+
[0,0,0,1,1]]
17+
18+
it('testing', () => {
19+
const res = rootTree(myGraph)
20+
expect(res.id).toStrictEqual(0)
21+
expect(res.children.length).toStrictEqual(1)
22+
expect(res.children[0].id).toStrictEqual(1)
23+
expect(res.children[0].children.length).toStrictEqual(2)
24+
expect(res.children[0].children[0].id).toStrictEqual(2)
25+
expect(res.children[0].children[1].id).toStrictEqual(3)
26+
expect(res.children[0].children[1].children.length).toStrictEqual(1)
27+
expect(res.children[0].children[1].children[0].id).toStrictEqual(4)
28+
})
29+
})

0 commit comments

Comments
 (0)