您的位置:首页 > Web前端

(php实现剑指offer)重建二叉树

2018-03-06 21:36 351 查看
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回<?php

/*class TreeNode{
var $val;
var $left = NULL;
var $right = NULL;
function __construct($val){
$this->val = $val;
}
}*/
function reConstructBinaryTree($pre, $vin)
{
// write code here
$root=reBtreeNode($pre,0,count($pre)-1,$vin,0,count($vin)-1);
return $root;
}
function reBtreeNode($pre,$pstart,$pend,$vin,$vstart,$vend)
{
if($pstart>$pend||$vstart>$vend){
return null;
}

$root=new TreeNode($pre[$pstart]);
for($i=$vstart;$i<=$vend;$i++){
if($pre[$pstart]==$vin[$i]){
$root->left=reBtreeNode($pre,$pstart+1,$i-$vstart+$pstart,$vin,$vstart,$i-1);
$root->right=reBtreeNode($pre,$i-$vstart+$pstart+1,$pend,$vin,$i+1,$vend);
break;
}
}

return $root;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: