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;
}
二叉树重建
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- 题目:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数...