阅读量:0
在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 }