基本能够完成任务的代码,请各位指正。
- #!/usr/bin/perl
- use strict;
- use warnings;
- while (<DATA>) {
- next if /^#/;
- next if /^\s*$/;
- chomp;
-
- print $_, "==>\n";
-
- my ($lnode, $rnode) = getNodes($_);
-
- if ($lnode =~ /^\(/) {
- my $str = $lnode;
-
- my ($lnode, $mnode) = getNodes($str);
-
- print join(',', ($lnode, $mnode, $rnode)), "\n";
- }
- else {
- my $str = $rnode;
-
- my ($mnode, $rnode) = getNodes($str);
-
- print join(',', ($lnode, $mnode, $rnode)), "\n";
- }
- }
- =begin
- Name: getNodes
- Desc: Get 2 nodes of a binary tree
- Usage: getNodes($str)
- Args: A string
- Return: 2 strings
- =cut
- sub getNodes {
- my ($str) = @_;
-
- # Remove leading and tailing parentheses
- # $str =~ s/^\(|\)$//g;
-
- # '((1,2),3)'
- if ($str =~ /^\((\(.+\)),(\w+)\)$/) {
- # print "L\n";
- return ($1, $2);
- }
- # '((1,2),(3,4))'
- elsif ($str =~ /^\((\(.+\)),(\(.+\))\)$/) {
- # print "M\n";
- return ($1, $2);
- }
- # '(1,(2,3))'
- elsif ($str =~ /^\((\w+),(\(.+\))\)$/) {
- # print "R\n";
- return ($1, $2);
- }
- # '(1,2)'
- elsif ($str =~ /^\((\w+),(\w+)\)$/) {
- return ($1, $2);
- }
- else {
- print "Error!\n";
- return (0, 0);
- }
- }
- __DATA__
- (((1,2),3),4)
- ((1,2),(3,4))
- (1,(2,(3,4)))
- ((1,2),(3,(4,5)))
- (((((1,2),3),4),(5,6))
复制代码 输出
- (((1,2),3),4)==>
- (1,2),3,4
- ((1,2),(3,4))==>
- 1,2,(3,4)
- (1,(2,(3,4)))==>
- 1,2,(3,4)
- ((1,2),(3,(4,5)))==>
- 1,2,(3,(4,5))
- (((((1,2),3),4),(5,6))==>
- (((1,2),3),4,(5,6)
复制代码 |