剑指offer(PHP版改写)----重建二叉树

输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
class TreeNode{
var $val;
var $left = NULL;
var $right = NULL;
function __construct($val){
$this->val = $val;
}
}
方法一:不使用php内置方法
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($root);
$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;
}

$pre = [1,2,4,7,3,5,6,8];
$vin = [4,7,2,1,5,3,8,6];
print_r(reConstructBinaryTree($pre,$vin));
方法二:使用php内置方法 array_search、array_slice
function reConstructBinaryTree($pre, $vin)
{
// write code here
if($pre && $vin){
$treeRoot = new TreeNode($pre[0]);
$index = array_search($pre[0],$vin);
$treeRoot->left = reConstructBinaryTree(array_slice($pre,1,$index),array_slice($vin,0,$index));
$treeRoot->right = reConstructBinaryTree(array_slice($pre,$index+1),array_slice($vin,$index+1));
return $treeRoot;
}
}

猜你喜欢

转载自www.cnblogs.com/cyworz/p/11225263.html