1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
class { var $val; var $left = NULL; var $right = NULL; function __construct($val){ $this->val = $val; } } function reConstructBinaryTree($pre, $vin) { 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; } } $pre = [1,2,4,7,3,5,6,8]; $vin = [4,7,2,1,5,3,8,6]; $re = reConstructBinaryTree($pre, $vin);
|
近期评论