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.
In reply to Re: Tree depth
by moritz
in thread Tree depth
by katarinahm
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |