剑指offer---4、序列化二叉树

剑指offer---4、序列化二叉树

一、总结

一句话总结:

1. 对于序列化:使用前序遍历,递归的将二叉树的值转化为字符,并且在每次二叉树的结点不为空时,在转化val所得的字符之后添加一个' , '作为分割。对于空节点则以 '#' 代替。
2. 对于反序列化:按照前序顺序,递归的使用字符串中的字符创建一个二叉树

1、对一个二叉树序列化是什么意思?

序列化就是将对象或者数组转化为 字符串

2、php自带序列化和反序列化函数么(序列化二叉树)?

带的:serialize($pRoot); unserialize($s);
<?php
 
/*class TreeNode{
    var $val;
    var $left = NULL;
    var $right = NULL;
    function __construct($val){
        $this->val = $val;
    }
}*/
function MySerialize($pRoot)
{
    // write code here
    return serialize($pRoot);
}
function MyDeserialize($s)
{
    // write code here
    return unserialize($s);
}

二、内容在总结中

1、题目描述

请实现两个函数,分别用来序列化和反序列化二叉树

 

2、代码

<?php
 
/*class TreeNode{
    var $val;
    var $left = NULL;
    var $right = NULL;
    function __construct($val){
        $this->val = $val;
    }
}*/
function MySerialize($pRoot)
{
    // write code here
    return serialize($pRoot);
}
function MyDeserialize($s)
{
    // write code here
    return unserialize($s);
}
<?php
 
/*class TreeNode{
    var $val;
    var $left = NULL;
    var $right = NULL;
    function __construct($val){
        $this->val = $val;
    }
}*/
function MySerialize($pRoot)
{
    if($pRoot == null)    return '#';
    $arr = [];
    preOrder($pRoot,$arr);
    $str = $arr[0];
    for($i=1;$i<count($arr);$i++)
        $str = $str." ".$arr[$i];
    return $str;
}
function preOrder($pRoot,&$arr){
    if($pRoot == null){
        $arr[] = '#';
        return ;
    }
    $arr[] = $pRoot->val;
    preOrder($pRoot->left,$arr);
    preOrder($pRoot->right,$arr);
    return ;
}
function MyDeserialize($s)
{
    $i = -1;
    $arr = explode(" ",$s);
    return reconstruct($arr,$i);
    
}
function reconstruct($arr,&$i){
    $i++;
    if($i >= count($arr))
        return null;
    if($arr[$i] == '#')
        return null;
    $node = new TreeNode($arr[$i]);
    $node->left = reconstruct($arr,$i);
    $node->right = reconstruct($arr,$i);
    return $node;
}
 
原文地址:https://www.cnblogs.com/Renyi-Fan/p/11037510.html