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 }
0 commit comments