-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFindDuplicateSubtrees.php
82 lines (67 loc) · 1.65 KB
/
FindDuplicateSubtrees.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
<?php
namespace HashTable\DesignTheKey\FindDuplicateSubtrees;
// 给定一棵二叉树,返回所有重复的子树。对于同一类的重复子树,你只需要返回其中任意一棵的根结点即可。
//
// 两棵树重复是指它们具有相同的结构以及相同的结点值。
//
// 示例 1:
//
// 1
// / \
// 2 3
// / / \
// 4 2 4
// /
// 4
// 下面是两个重复的子树:
//
// 2
// /
// 4
// 和
//
// 4
// 因此,你需要以列表的形式返回上述重复子树的根结点。
/**
* Definition for a binary tree node.
*/
class TreeNode
{
public $val = null;
public $left = null;
public $right = null;
function __construct($value)
{
$this->val = $value;
}
}
class Solution
{
protected $map = [];
protected $rootNodes = [];
/**
* @param TreeNode $root
* @return TreeNode[]
*/
public function findDuplicateSubtrees($root)
{
$this->serialize($root);
return $this->rootNodes;
}
protected function serialize($root)
{
if (is_null($root)) {
return '#';
}
$code = "{$root->val}," . $this->serialize($root->left) . "," . $this->serialize($root->right);
// 只记录第一次
if (
array_key_exists($code, $this->map) &&
$this->map[$code] === 1
) {
array_push($this->rootNodes, $root);
}
$this->map[$code] = ($this->map[$code] ?? 0) + 1;
return $code;
}
}