二叉树重建

2017-07-05  本文已影响9人  followyounger1
function reConstructBinaryTree($pre, $vin)
{
  // write code here
  return build($pre,$vin,0,count($pre)-1,0,count($vin)-1);
}
function build($pre,$inorder,$pstart,$pend,$istart,$iend){
      if($pstart>$pend||$istart>$iend)
        return;
    $root=$pre[$pstart];
      for($find=$istart;$find<=$iend;$find++){
        if($root===$inorder[$find]){
        break;
        }
}
$len=$find-$istart;
$res=new TreeNode($inorder[$find]);
$res->left=build($pre,$inorder,$pstart+1,$pstart+$len,$istart,$find-1);
$res->right=build($pre,$inorder,$pstart+$len+1,$pend,$find+1,count($inorder)-1);
return $res;
}
上一篇 下一篇

猜你喜欢

热点阅读