Skip to content

Commit a83edac

Browse files
authored
feat: add solutions to lc problem: No.0449 (doocs#1571)
No.0449.Serialize and Deserialize BST
1 parent ff708ad commit a83edac

File tree

6 files changed

+637
-222
lines changed

6 files changed

+637
-222
lines changed

solution/0400-0499/0449.Serialize and Deserialize BST/README.md

+199-52
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,14 @@
4242

4343
<!-- 这里可写通用的实现逻辑 -->
4444

45+
**方法一:先序遍历**
46+
47+
题目给定的是二叉搜索树,我们知道二叉搜索树的中序遍历是有序的,而通过“先序遍历”和“中序遍历”可以唯一确定一棵二叉树,所以我们可以通过先序遍历的结果和中序遍历的结果来唯一确定一棵二叉搜索树。
48+
49+
`serialize` 方法中,我们使用先序遍历的方式将二叉搜索树序列化为空格分隔的字符串,然后在 `deserialize` 方法中,我们将字符串按空格分割为数组,然后使用递归的方式来构建二叉搜索树。递归函数为 $dfs(mi, mx)$,表示当前节点的值必须在 $[mi, mx]$ 之间,如果当前节点的值不在 $[mi, mx]$ 之间,则说明这个节点不是当前递归树的节点,返回 `None`
50+
51+
时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉搜索树的节点数。
52+
4553
<!-- tabs:start -->
4654

4755
### **Python3**
@@ -58,44 +66,37 @@
5866

5967

6068
class Codec:
61-
def serialize(self, root: TreeNode) -> str:
69+
def serialize(self, root: Optional[TreeNode]) -> str:
6270
"""Encodes a tree to a single string."""
6371

64-
def dfs(root):
72+
def dfs(root: Optional[TreeNode]):
6573
if root is None:
6674
return
67-
nonlocal t
68-
t.append(str(root.val))
69-
t.append(',')
75+
nums.append(root.val)
7076
dfs(root.left)
7177
dfs(root.right)
7278

73-
if root is None:
74-
return ''
75-
t = []
79+
nums = []
7680
dfs(root)
77-
return ''.join(t[:-1])
81+
return " ".join(map(str, nums))
7882

79-
def deserialize(self, data: str) -> TreeNode:
83+
def deserialize(self, data: str) -> Optional[TreeNode]:
8084
"""Decodes your encoded data to tree."""
8185

82-
def build(s, l, r):
83-
if l > r:
86+
def dfs(mi: int, mx: int) -> Optional[TreeNode]:
87+
nonlocal i
88+
if i == len(nums) or not mi <= nums[i] <= mx:
8489
return None
85-
root = TreeNode(int(s[l]))
86-
idx = r + 1
87-
for i in range(l + 1, r + 1):
88-
if int(s[i]) > root.val:
89-
idx = i
90-
break
91-
root.left = build(s, l + 1, idx - 1)
92-
root.right = build(s, idx, r)
90+
x = nums[i]
91+
root = TreeNode(x)
92+
i += 1
93+
root.left = dfs(mi, x)
94+
root.right = dfs(x, mx)
9395
return root
9496

95-
if not data:
96-
return None
97-
s = data.split(',')
98-
return build(s, 0, len(s) - 1)
97+
nums = list(map(int, data.split()))
98+
i = 0
99+
return dfs(-inf, inf)
99100

100101

101102
# Your Codec object will be instantiated and called as such:
@@ -122,49 +123,48 @@ class Codec:
122123
* }
123124
*/
124125
public class Codec {
126+
private int i;
127+
private List<String> nums;
128+
private final int inf = 1 << 30;
125129

126130
// Encodes a tree to a single string.
127131
public String serialize(TreeNode root) {
128-
if (root == null) {
129-
return "";
130-
}
131-
StringBuilder sb = new StringBuilder();
132-
dfs(root, sb);
133-
return sb.substring(0, sb.length() - 1);
134-
}
135-
136-
private void dfs(TreeNode root, StringBuilder sb) {
137-
if (root == null) {
138-
return;
139-
}
140-
sb.append(root.val).append(",");
141-
dfs(root.left, sb);
142-
dfs(root.right, sb);
132+
nums = new ArrayList<>();
133+
dfs(root);
134+
return String.join(" ", nums);
143135
}
144136

145137
// Decodes your encoded data to tree.
146138
public TreeNode deserialize(String data) {
147139
if (data == null || "".equals(data)) {
148140
return null;
149141
}
150-
String[] s = data.split(",");
151-
return build(s, 0, s.length - 1);
142+
i = 0;
143+
nums = Arrays.asList(data.split(" "));
144+
return dfs(-inf, inf);
152145
}
153146

154-
private TreeNode build(String[] s, int l, int r) {
155-
if (l > r) {
147+
private void dfs(TreeNode root) {
148+
if (root == null) {
149+
return;
150+
}
151+
nums.add(String.valueOf(root.val));
152+
dfs(root.left);
153+
dfs(root.right);
154+
}
155+
156+
private TreeNode dfs(int mi, int mx) {
157+
if (i == nums.size()) {
156158
return null;
157159
}
158-
int idx = r + 1;
159-
TreeNode root = new TreeNode(Integer.valueOf(s[l]));
160-
for (int i = l + 1; i <= r; ++i) {
161-
if (Integer.valueOf(s[i]) > root.val) {
162-
idx = i;
163-
break;
164-
}
160+
int x = Integer.parseInt(nums.get(i));
161+
if (x < mi || x > mx) {
162+
return null;
165163
}
166-
root.left = build(s, l + 1, idx - 1);
167-
root.right = build(s, idx, r);
164+
TreeNode root = new TreeNode(x);
165+
++i;
166+
root.left = dfs(mi, x);
167+
root.right = dfs(x, mx);
168168
return root;
169169
}
170170
}
@@ -177,6 +177,153 @@ public class Codec {
177177
// return ans;
178178
```
179179

180+
### **C++**
181+
182+
```cpp
183+
/**
184+
* Definition for a binary tree node.
185+
* struct TreeNode {
186+
* int val;
187+
* TreeNode *left;
188+
* TreeNode *right;
189+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
190+
* };
191+
*/
192+
class Codec {
193+
public:
194+
195+
// Encodes a tree to a single string.
196+
string serialize(TreeNode* root) {
197+
if (!root) {
198+
return "";
199+
}
200+
string data = "";
201+
function<void(TreeNode*)> dfs = [&](TreeNode* root) {
202+
if (!root) {
203+
return;
204+
}
205+
data += to_string(root->val) + " ";
206+
dfs(root->left);
207+
dfs(root->right);
208+
};
209+
dfs(root);
210+
data.pop_back();
211+
return data;
212+
}
213+
214+
// Decodes your encoded data to tree.
215+
TreeNode* deserialize(string data) {
216+
if (data.empty()) {
217+
return nullptr;
218+
}
219+
vector<int> nums = split(data, ' ');
220+
int i = 0;
221+
function<TreeNode*(int, int)> dfs = [&](int mi, int mx) -> TreeNode* {
222+
if (i == nums.size() || nums[i] < mi || nums[i] > mx) {
223+
return nullptr;
224+
}
225+
int x = nums[i++];
226+
TreeNode* root = new TreeNode(x);
227+
root->left = dfs(mi, x);
228+
root->right = dfs(x, mx);
229+
return root;
230+
};
231+
return dfs(INT_MIN, INT_MAX);
232+
}
233+
234+
vector<int> split(const string& s, char delim) {
235+
vector<int> tokens;
236+
stringstream ss(s);
237+
string token;
238+
while (getline(ss, token, delim)) {
239+
tokens.push_back(stoi(token));
240+
}
241+
return tokens;
242+
}
243+
};
244+
245+
// Your Codec object will be instantiated and called as such:
246+
// Codec* ser = new Codec();
247+
// Codec* deser = new Codec();
248+
// string tree = ser->serialize(root);
249+
// TreeNode* ans = deser->deserialize(tree);
250+
// return ans;
251+
```
252+
253+
### **Go**
254+
255+
```go
256+
/**
257+
* Definition for a binary tree node.
258+
* type TreeNode struct {
259+
* Val int
260+
* Left *TreeNode
261+
* Right *TreeNode
262+
* }
263+
*/
264+
265+
type Codec struct {
266+
}
267+
268+
func Constructor() Codec {
269+
return Codec{}
270+
}
271+
272+
// Serializes a tree to a single string.
273+
func (this *Codec) serialize(root *TreeNode) string {
274+
if root == nil {
275+
return ""
276+
}
277+
data := &strings.Builder{}
278+
var dfs func(*TreeNode)
279+
dfs = func(root *TreeNode) {
280+
if root == nil {
281+
return
282+
}
283+
data.WriteString(strconv.Itoa(root.Val))
284+
data.WriteByte(' ')
285+
dfs(root.Left)
286+
dfs(root.Right)
287+
}
288+
dfs(root)
289+
return data.String()[0 : data.Len()-1]
290+
}
291+
292+
// Deserializes your encoded data to tree.
293+
func (this *Codec) deserialize(data string) *TreeNode {
294+
if data == "" {
295+
return nil
296+
}
297+
vals := strings.Split(data, " ")
298+
i := 0
299+
var dfs func(int, int) *TreeNode
300+
dfs = func(mi, mx int) *TreeNode {
301+
if i == len(vals) {
302+
return nil
303+
}
304+
x, _ := strconv.Atoi(vals[i])
305+
if x < mi || x > mx {
306+
return nil
307+
}
308+
i++
309+
root := &TreeNode{Val: x}
310+
root.Left = dfs(mi, x)
311+
root.Right = dfs(x, mx)
312+
return root
313+
}
314+
return dfs(math.MinInt64, math.MaxInt64)
315+
}
316+
317+
/**
318+
* Your Codec object will be instantiated and called as such:
319+
* ser := Constructor()
320+
* deser := Constructor()
321+
* tree := ser.serialize(root)
322+
* ans := deser.deserialize(tree)
323+
* return ans
324+
*/
325+
```
326+
180327
### **...**
181328

182329
```

0 commit comments

Comments
 (0)