🔢
Algorithms & Data
Ctrlk
  • Overview
    • 1. Sort
    • 2. Data Structures
    • 3. How to construct Algorithm? Paradigm
  • Algorithm Problems
    • Problem Sources
    • AlgoExpert
    • Daily Algorithms
  • Top 75 LeetCode Questions to Save Your Time
    • Source
    • Problems
      • Interval
      • Heap
      • Array
      • Binary
      • Graph
      • Tree
        • x 297. Serialize and Deserialize Binary Tree
        • x 105. Construct Binary Tree from Preorder and Inorder Traversal
        • x 212. Word Search II
        • 211. Design Add and Search Words Data Structure
        • 208. Implement Trie (Prefix Tree)
        • 235. Lowest Common Ancestor of a Binary Search Tree
        • 230. Kth Smallest Element in a BST
        • 98. Validate Binary Search Tree
        • 572. Subtree of Another Tree
        • 297. Serialize and Deserialize Binary Tree ?
        • 102. Binary Tree Level Order Traversal
        • 124. Binary Tree Maximum Path Sum
        • 226. Invert Binary Tree
        • 100. Same Tree
        • 104. Maximum Depth of Binary Tree
      • Dynamic Programming
      • String
      • Matrix
      • Linked List
  • Tip
    • Page 2
    • LinkedList
Powered by GitBook
On this page
  1. Top 75 LeetCode Questions to Save Your Time
  2. Problems
  3. Tree

x 297. Serialize and Deserialize Binary Tree

LogoSerialize and Deserialize Binary Tree - LeetCodeLeetCode

LeetCode - The World's Leading Online Programming Learning Platform

time: O(n)

space: O(n)

PreviousTreeNextx 105. Construct Binary Tree from Preorder and Inorder Traversal

Last updated 16 days ago

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */

/**
 * Encodes a tree to a single string.
 *
 * @param {TreeNode} root
 * @return {string}
 */
let arr = [];
var serialize = function (root, idx = 0) {
    arr = [];
    serializeHelper(root);
    return arr.join(',');;
};

function serializeHelper(root, idx = 0) {
    if (root === null) {
        arr.push('null');
        return;
    }

    arr.push(root.val);
    const left = serializeHelper(root.left);
    const right = serializeHelper(root.right);
    return arr;
}

/**
 * Decodes your encoded data to tree.
 *
 * @param {string} data
 * @return {TreeNode}
 */
 let idx;
var deserialize = function (data) {
    idx = 0;
    arr = data.split(',')
    return deserializeHelper(arr);
};

function deserializeHelper(arr) {
    if (idx >= arr.length) return null;

    if (arr[idx] === 'null') {
        idx++;
        return null;
    }

    const root = new TreeNode(Number(arr[idx]));
    idx++;
    root.left = deserializeHelper(arr);
    root.right = deserializeHelper(arr);

    return root;
}

/**
 * Your functions will be called as such:
 * deserialize(serialize(root));
 */