溫馨提示×

php二叉樹如何進(jìn)行序列化

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

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

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

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

$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