闲着无聊花了两个多小时才写好
交换前:
1
2 3
10 4 5
6 11 13
7 12
8 9
交换后:
1
3 2
5 4 10
13 11 6
12 7
9 8
<? $tree=array( array(0,1), array(1,2), array(1,3), array(3,4), array(3,5), array(5,6), array(6,7), array(7,8), array(7,9), array(2,10), array(5,11), array(6,12), array(5,13) ); $alllink=array(); $x=getLink(); echo "交换前..... "; formatOutput($x); swapNode((parseLink($x))); $x=getLink(); echo "交换后... "; formatOutput($x); function formatOutput($arr){ foreach($arr as $v){ echo $v." "; } } function swapNode($arr){ global $tree; $ntree=$tree; for($i=0;$i<$arr[0];$i++){ $swap=array(); foreach($arr[1] as $v){ if(isset($v[$i])){ if(!in_array($v[$i],$swap))$swap[]=$v[$i]; } } if(count($swap)<2) continue; $rswap=array_reverse($swap);//反转,以便交换时一一对应 for($j=0;$j<count($swap);$j++){ foreach($tree as $k1=>$v1){ if($v1[1]==$swap[$j]){ $ntree[$k1]=array($ntree[$k1][0],$rswap[$j]);//当前节点交换,存储在新树中 foreach($tree as $k2=>$v2){ if($v2[0]==$swap[$j]){ $ntree[$k2]=array($rswap[$j],$ntree[$k2][1]);//子节点交换,存储在新树中 } } } } } } $tree=$ntree; } function parseLink($arr){ $r=array(); $maxLen=0; foreach($arr as $v){ $t=explode("#",$v); if(count($t)>$maxLen)$maxLen=count($t); $r[]=explode("#",$v); } return array($maxLen,$r); } function getLink($pid=0){ global $tree; $link=array(); foreach($tree as $k=>$v){ if($pid==$v[0]){ $cid=getLink($v[1]); if(count($cid)>0){ foreach($cid as $v1){ $link[]=$v[1]."#".$v1; } }else{ $link[]=$v[1]; } } } return $link; } ?>
交换前.....
1#2#10
1#3#4
1#3#5#6#7#8
1#3#5#6#7#9
1#3#5#6#12
1#3#5#11
1#3#5#13
交换后...
1#3#5
1#2#4
1#2#10#13#12#9
1#2#10#13#12#8
1#2#10#13#7
1#2#10#11
1#2#10#6