首页 > 其他 > 详细

面试题7:重建二叉树

时间:2018-12-02 18:20:46      阅读:137      评论:0      收藏:0      [点我收藏+]
<?php
header("content-type:text/html;charset=utf-8");
/*
 *重建二叉树 P62
 */
class TreeNode
{
    var $val;
    var $left = NULL;
    var $right = NULL;

    function __construct($val)
    {
        $this->val = $val;
    }
}
function reConstructBinaryTree($pre, $vin)
{
    if($pre == null || $vin == null){
        return false;
    }

    $rootValue = $pre[0];
    $root = new TreeNode($rootValue);

    $index = array_search($pre[0],$vin);
    $pre_left = array_slice($pre,1,$index);    //1是数组的截取的起始索引位置,index是截取的长度,而不是截取的结束索引位置!!!并且截取之后原数组pre的长度不变
    $vin_left = array_slice($vin,0,$index);
    $root->left = reConstructBinaryTree($pre_left,$vin_left);

    $pre_right = array_slice($pre,$index + 1);
    $vin_right = array_slice($vin,$index + 1);

    $root->right = reConstructBinaryTree($pre_right,$vin_right);

    return $root;

}

$pre = array(1,2,4,7,3,5,6,8);
$vin = array(4,7,2,1,5,3,8,6);

print_r(reConstructBinaryTree($pre,$vin));

 

面试题7:重建二叉树

原文:https://www.cnblogs.com/xlzfdddd/p/10054370.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!