劍指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;
}

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM