in reply to Tree depth
Tree depth is a classical example for Depth-first search:
use strict; use warnings; use List::Util qw/max/; my $graphspec = '1 -> 2 2 -> 0 3 -> 4 4 -> 2 5 -> 10 6 -> 10 7 -> 9 8 +-> 9 9 -> 6 10 -> 4 11 -> 10 12 -> 10 13 -> 12 14 -> 10 15 -> 2'; my %graph; while ($graphspec =~ /(\d+)\s+->\s+(\d+)/g) { $graph{$1} = $2; } sub depth { return max map { $_and 1 + depth($graph{$_}) } @_; } print depth(keys %graph);
Update: this produces the largest distance to the root, not the height. The difference is 1, ie the height is always one larger than the distance to the root. Easy to fix if you do want the tree height.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Tree depth
by katarinahm (Initiate) on Mar 13, 2012 at 10:41 UTC | |
|
Re^2: Tree depth
by katarinahm (Initiate) on Mar 13, 2012 at 13:44 UTC | |
by moritz (Cardinal) on Mar 13, 2012 at 13:54 UTC | |
by katarinahm (Initiate) on Mar 13, 2012 at 14:57 UTC | |
by moritz (Cardinal) on Mar 13, 2012 at 15:15 UTC | |
by katarinahm (Initiate) on Mar 13, 2012 at 15:44 UTC | |
|