-
Notifications
You must be signed in to change notification settings - Fork 143
/
Copy path14.php
55 lines (46 loc) · 954 Bytes
/
14.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<?php
/**
* 请实现两个函数,分别用来序列化和反序列化二叉树
*/
/*class TreeNode{
var $val;
var $left = NULL;
var $right = NULL;
function __construct($val){
$this->val = $val;
}
}*/
function MySerialize($pRoot)
{
$arr = [];
doSerialize($pRoot, $arr);
return implode(',', $arr);
}
function doSerialize($pRoot, &$arr)
{
if (empty($pRoot)) {
$arr[] = '#';
return;
}
$arr[] = $pRoot->val;
doSerialize($pRoot->left, $arr);
doSerialize($pRoot->right, $arr);
}
function MyDeserialize($s)
{
$arr = explode(',', $s);
$i = -1;
return doDeserialize($arr, $i);
}
function doDeserialize($arr, &$i)
{
$i++;
if ($i >= count($arr)) {
return null;
}
if ($arr[$i] == '#') return null;
$node = new TreeNode($arr[$i]);
$node->left = doDeserialize($arr, $i);
$node->right = doDeserialize($arr, $i);
return $node;
}