代碼思路:根據給出的兩種遍曆順序,構造出一顆樹,然後再遍曆出剩下的一種遍曆。
中根遍曆+後根遍曆 求 前根遍曆
#!/usr/bin/perl -w<br />use strict;<br />use List::Util qw(first);<br />use 5.010;<br />my @Tree;<br />my $top;<br />my @s1;<br />my @s2;<br />sub getTree($$){<br /> my($a, $b) = @_;<br /> return -1 if $a > $b;<br /> if($a == $b){<br /> $Tree[$top]->{lf} = $Tree[$top]->{rh} = -1;<br /> $Tree[$top]->{c} = $s1[$a];<br /> return $top++;<br /> }<br /> my $k = $top++;<br /> my $j = first {$s1[$_] eq $s2[$#s2-$k]}$a..$b;</p><p> $Tree[$k]->{c} = $s1[$j];<br /> $Tree[$k]->{rh} = &getTree($j+1,$b);<br /> $Tree[$k]->{lf} = &getTree($a, $j-1);<br /> return $k;<br />}<br />sub print_tree($){<br /> my $n = shift;<br /> return if $n == -1;<br /> print $Tree[$n]->{c};<br /> &print_tree($Tree[$n]->{lf});<br /> &print_tree($Tree[$n]->{rh});<br />}<br />my $line = <STDIN>;<br />last if $line eq '/n';<br />my($str1, $str2) = split ' ',$line;<br />@s1 = split '', $str1;<br />@s2 = split '', $str2;<br />$top = 0;<br />my $k = $top++;<br />my $j = first { $s1[$_] eq $s2[$#s2] }0..$#s1;</p><p>$Tree[$k]->{c} = $s2[-1];<br />$Tree[$k]->{rh} = getTree( $j+1, $#s2 );<br />$Tree[$k]->{lf} = getTree( 0 , $j - 1);<br />print_tree(0);<br />print "/n";</p><p> #DGBAECFHJI GDBEJIHFCA ------->ABDGCEFHIJ
中根遍曆+前根遍曆 求 後根遍曆
#!/usr/bin/perl -w<br />use strict;<br />use List::Util qw(first);<br />my @Tree ;<br />my $top;<br />my @s1;<br />my @s2;</p><p>sub getNode($$){<br /> my($a, $b) = @_;<br /> return -1 if $a > $b;<br /> if($a == $b){<br /> $Tree[$top]->{lf} = $Tree[$top]->{rh} = -1;<br /> $Tree[$top]->{c} = $s1[$top];<br /> return $top++;<br /> }<br /> my $k = $top++;<br /> $Tree[$k]->{c} = $s1[$k];<br /> my $i = first{$s2[$_] eq $s1[$k]}$a..$b;</p><p> $Tree[$k]->{lf} = &getNode($a, $i-1);<br /> $Tree[$k]->{rh} = &getNode($i+1,$b);<br /> return $k;<br />}</p><p>sub print_tree($){<br /> my $n = shift;<br /> return if $n == -1;<br /> &print_tree($Tree[$n]->{lf});<br /> &print_tree($Tree[$n]->{rh});<br /> print $Tree[$n]->{c};<br />}</p><p>while(my $line = <STDIN>){<br /> last if $line eq '/n';<br /> my($str1, $str2) = split ' ',$line;<br /> @s1 = split '', $str1;<br /> @s2 = split '', $str2;<br /> $top = 0;<br /> my $k = $top++;<br /> $Tree[$k]->{c} = $s1[0];<br /> my $j = first {$s1[0] eq $s2[$_] } 0..$#s1;</p><p> $Tree[$k]->{lf} = getNode( 0 , $j - 1);<br /> $Tree[$k]->{rh} = getNode( $j+1, $#s2 );<br /> print_tree(0);<br /> print "/n";<br />}