Skip to main content
Back to problems
#297
Hard Algorithms

Serialize and deserialize binary tree

String Tree Depth-First Search Breadth-First Search Design Binary Tree
60.4% acceptance
Jan 12, 2026
11093
434
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. 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. Clarification: The input/output format is the same as how LeetCode serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
* impl Codec {
 *     fn new() -> Self {

 *     }

 *     fn serialize(&self, root: Option<Rc<RefCell<TreeNode>>>) -> String {

 *     }

 *     fn deserialize(&self, data: String) -> Option<Rc<RefCell<TreeNode>>> {

 *     }
 * }
 */

use std::rc::Rc;
use std::cell::RefCell;

struct Codec {}

impl Codec {
  fn new() -> Self {
    Codec {}
  }

  fn serialize(&self, root: Option<Rc<RefCell<TreeNode>>>) -> String {
    let mut result = Vec::new();
    self.serialize_helper(root, &mut result);
    result.join(",")
  }
  
  fn serialize_helper(&self, node: Option<Rc<RefCell<TreeNode>>>, result: &mut Vec<String>) {
    match node {
      None => result.push("null".to_string()),
      Some(n) => {
        let n = n.borrow();
        result.push(n.val.to_string());
        self.serialize_helper(n.left.clone(), result);
        self.serialize_helper(n.right.clone(), result);
      }
    }
  }

  fn deserialize(&self, data: String) -> Option<Rc<RefCell<TreeNode>>> {
    let vals: Vec<&str> = data.split(',').collect();
    let mut index = 0;
    self.deserialize_helper(&vals, &mut index)
  }
  
  fn deserialize_helper(&self, vals: &[&str], index: &mut usize) -> Option<Rc<RefCell<TreeNode>>> {
    if *index >= vals.len() || vals[*index] == "null" {
      *index += 1;
      return None;
    }
    
    let val = vals[*index].parse::<i32>().unwrap();
    *index += 1;
    let left = self.deserialize_helper(vals, index);
    let right = self.deserialize_helper(vals, index);
    
    Some(Rc::new(RefCell::new(TreeNode {
      val,
      left,
      right,
    })))
  }
}