Code idea: Construct a tree based on the given two traversal sequences, and then traverse the remaining traversal.
Root traversal + root Traversal
#! /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]} $ .. $ 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
Root traversal + root traversal find root Traversal
#! /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]} $ .. $ 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/>}