297. Serialize and Deserialize Binary Tree Hard
1/**
2 * [297] Serialize and Deserialize Binary Tree
3 *
4 * Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.
5 * Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.
6 * Clarification: The input/output format is the same as <a href="https://support.leetcode.com/hc/en-us/articles/360011883654-What-does-1-null-2-3-mean-in-binary-tree-representation-" target="_blank">how LeetCode serializes a binary tree</a>. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.
7 *
8 * Example 1:
9 * <img alt="" src="https://assets.leetcode.com/uploads/2020/09/15/serdeser.jpg" style="width: 442px; height: 324px;" />
10 * Input: root = [1,2,3,null,null,4,5]
11 * Output: [1,2,3,null,null,4,5]
12 *
13 * Example 2:
14 *
15 * Input: root = []
16 * Output: []
17 *
18 *
19 * Constraints:
20 *
21 * The number of nodes in the tree is in the range [0, 10^4].
22 * -1000 <= Node.val <= 1000
23 *
24 */
25pub struct Solution {}
26use crate::util::tree::{TreeNode, to_tree};
27
28// problem: https://leetcode.com/problems/serialize-and-deserialize-binary-tree/
29// discuss: https://leetcode.com/problems/serialize-and-deserialize-binary-tree/discuss/?currentPage=1&orderBy=most_votes&query=
30
31// submission codes start here
32
33// Definition for a binary tree node.
34// #[derive(Debug, PartialEq, Eq)]
35// pub struct TreeNode {
36// pub val: i32,
37// pub left: Option<Rc<RefCell<TreeNode>>>,
38// pub right: Option<Rc<RefCell<TreeNode>>>,
39// }
40//
41// impl TreeNode {
42// #[inline]
43// pub fn new(val: i32) -> Self {
44// TreeNode {
45// val,
46// left: None,
47// right: None
48// }
49// }
50// }
51use std::rc::Rc;
52use std::cell::RefCell;
53struct Codec {
54
55}
56
57/**
58 * `&self` means the method takes an immutable reference.
59 * If you need a mutable reference, change it to `&mut self` instead.
60 */
61impl Codec {
62 fn new() -> Self {
63 String::new()
64 }
65
66 fn serialize(&self, root: Option<Rc<RefCell<TreeNode>>>) -> String {
67
68 }
69
70 fn deserialize(&self, data: String) -> Option<Rc<RefCell<TreeNode>>> {
71
72 }
73}
74
75/**
76 * Your Codec object will be instantiated and called as such:
77 * let obj = Codec::new();
78 * let data: String = obj.serialize(strs);
79 * let ans: Option<Rc<RefCell<TreeNode>>> = obj.deserialize(data);
80 */
81
82// submission codes end
83
84#[cfg(test)]
85mod tests {
86 use super::*;
87
88 #[test]
89 fn test_297() {
90 }
91}
92
Back
© 2025 bowen.ge All Rights Reserved.