@@ -503,7 +503,48 @@ Then prune them, and update the degree values.
503
503
504
504
When you're left with either 1 or 2 nodes you've found the center or centers.
505
505
506
- I really love this algorithm which
506
+ Ok, let's have a look at some pseudo-code. Real code can be found in the
507
+ description.
508
+
509
+ The tree centers function takes as input a tree represented as an undirected
510
+ graph stored in the variable 'g'.
511
+
512
+ The variable 'n' represents the number of nodes in our tree.
513
+
514
+ After this, I define two arrays. The first one is 'degree' of length 'n' which
515
+ will capture the degree of each node, and 'leaves' is an array that contains the
516
+ most recent layer of leaf nodes.
517
+
518
+ Then for the first bit of logic simply loop through all the nodes and compute
519
+ the degree of each one. I do this by inspecting the adjacency list and counting
520
+ the number of edges coming out of each node.
521
+
522
+ Then, if the node has a degree of 0, meaning we're dealing with a single node
523
+ tree or the node is a leaf node because it has a degree of 1 then add the node
524
+ to the leaves array.
525
+
526
+ The way we're going to know when we've found the center or centers is when we
527
+ have processed all the nodes in the tree. The variable count is going to keep
528
+ track how many nodes we've processed so far. Every iteration we're going to
529
+ increment count by the number of leaves we found in the last layer.
530
+
531
+ Entering the loop, 'new_leaves' is a new array that will contain the new leaf
532
+ nodes on the next layer. I'm using a new array to avoid interfering with the
533
+ leaf nodes on the current layer.
534
+
535
+ So for every leaf node on the current layer,
536
+
537
+ process all the neighbors of those nodes
538
+
539
+ and decrement the degree of the neighbor nodes. Since we're removing the current
540
+ node this means that the degree of the neighboring node needs to go down. If the
541
+ neighbor node after being decremented has a degree of 1 then we know it will be
542
+ in the next layer of leaf nodes so add it to the new leaves array.
543
+
544
+ When we've finished processing the current layer increment the count variable
545
+ and replaces the leaves array with the new leaves.
546
+
547
+ And finally return the centers
507
548
508
549
--------------------------------------------------------------------
509
550
--------------------------------------------------------------------
0 commit comments