Wins the offer (PHP version rewritten) ---- reconstruction of a binary tree

And enter the result in a preorder traversal of a binary tree in preorder traversal of the binary tree a rebuild. Suppose Results preorder traversal order and input of duplicate numbers are free. 
Before entering e.g. preorder traversal sequence {1,2,4,7,3,5,6,8} and {4,7,2,1,5,3,8,6} order traversal sequence, and the reconstructed binary tree return.
the TreeNode {class
var $ Val;
var $ left = NULL;
var $ right = NULL;
function the __construct (Val $) {
$ this-> = $ Val Val;
}
}
Method a: built-in method without using php
function reConstructBinaryTree ($ pre , $ VIN)
{
// Write code here Wallpaper
return Build (pre $, $ VIN, 0, COUNT ($ pre) -1, 0, COUNT ($ VIN) -1);
}

function Build (pre $, $ InOrder, Pstart $, $ PEND, ISTART $, $ IEND) {

IF (Pstart $> $ $ ISTART PEND ||> $ IEND) {
return;
}
$ $ = the root pre [$ Pstart];
// root node acquired in sequence traversal subscript
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));
Method two: using php built-in methods 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;
}
}

Guess you like

Origin www.cnblogs.com/cyworz/p/11225263.html