91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

php二叉樹如何進行序列化

PHP
小樊
81
2024-10-17 19:43:05
欄目: 編程語言

在PHP中,可以使用序列化將二叉樹轉換為字符串表示形式,以便存儲或傳輸。以下是一個簡單的PHP類,用于表示二叉樹節點以及實現序列化和反序列化的方法:

class TreeNode {
    public $val;
    public $left;
    public $right;

    public function __construct($val = 0, $left = null, $right = null) {
        $this->val = $val;
        $this->left = $left;
        $this->right = $right;
    }
}

class Codec {

    // Encodes a tree to a single string.
    public function serialize($root) {
        if ($root === null) {
            return 'null,';
        }
        return $root->val . ',' . $this->serialize($root->left) . ',' . $this->serialize($root->right);
    }

    // Decodes your encoded data to tree.
    public function deserialize($data) {
        $dataArray = explode(',', trim($data, '[]'));
        return $this->buildTree($dataArray);
    }

    private function buildTree($dataArray) {
        if (empty($dataArray)) {
            return null;
        }
        $val = array_shift($dataArray);
        if ($val === 'null') {
            return null;
        }
        $node = new TreeNode($val);
        $node->left = $this->buildTree($dataArray);
        $node->right = $this->buildTree($dataArray);
        return $node;
    }
}

使用此類,您可以創建一個二叉樹節點實例,序列化它,然后將其反序列化回原始結構。以下是如何使用此類的示例:

$root = new TreeNode(1);
$root->left = new TreeNode(2);
$root->right = new TreeNode(3);
$root->right->left = new TreeNode(4);
$root->right->right = new TreeNode(5);

$codec = new Codec();
$serialized = $codec->serialize($root);
echo "Serialized tree: " . $serialized . PHP_EOL; // 輸出:Serialized tree: 1,2,null,null,3,4,null,null,5,

$deserialized = $codec->deserialize($serialized);
var_dump($deserialized); // 輸出:object(TreeNode)#3 (3) { ["val"]=> int(1) ["left"]=> object(TreeNode)#4 (3) { ["val"]=> int(2) ["left"]=> object(TreeNode)#5 (3) { ["val"]=> int(4) ["left"]=> NULL ["right"]=> NULL } ["right"]=> NULL } ["right"]=> object(TreeNode)#6 (3) { ["val"]=> int(3) ["left"]=> NULL ["right"]=> NULL } ["right"]=> object(TreeNode)#7 (3) { ["val"]=> int(5) ["left"]=> NULL ["right"]=> NULL } } ["left"]=> NULL ["right"]=> NULL }

0
安化县| 淮北市| 宣汉县| 龙南县| 陇南市| 金沙县| 望城县| 东源县| 赤城县| 伊川县| 满洲里市| 郎溪县| 军事| 海城市| 永康市| 洪湖市| 郧西县| 简阳市| 通渭县| 永宁县| 伊宁县| 聂拉木县| 屏东市| 河北区| 井陉县| 根河市| 新源县| 安乡县| 义马市| 康保县| 萨迦县| 东兴市| 繁峙县| 鹤庆县| 阿拉善右旗| 横峰县| 宽甸| 温州市| 盐亭县| 鹤岗市| 四川省|