💻
Algorithm
  • README
  • Array
    • At Most To Equal
    • Count Inversions In An Array
    • Interleaving Placement
    • Kadane
    • Left To Right State Transition
    • Permutation
    • Quick Select
    • Sliding Window
    • Two Pointers
  • Binary Tree
    • Avl Tree
    • Binary Search Tree
    • Serialization And Deserialization
    • Traversal
  • Company
    • Facebook
  • Cpp
    • Array
    • Memset 3 F
    • Overflow
  • Data Structure
    • Binary Indexed Tree
    • Segment Tree And Binary Index Tree
    • Segment Tree
    • Stack
    • Trie
    • Union Find
  • Dynamic Programming
    • Knapsack
      • 0 1 Knapsack
      • Bounded Knapsack
      • Unbounded Knapsack
    • Bitmask Dp
    • Dp On Subsets
    • Dp On Tree
    • Dp With Sorting
    • Selective State Dp
    • Travelling Salesperson
  • Graph
    • Minimum Spanning Tree
      • Kruskal
      • Prim
    • Shortest Path
      • Bellman Ford
      • Dijkstra
      • Floyd Warshall
      • Johnson
      • Shortest Path Faster Algorithm
    • Bi Directional Breadth First Search
    • Bipartite
    • Breadth First Search
    • Component Coloring
    • Component Count
    • Depth First Search
    • Eulerian Path
    • Maximum Bipartite Matching
    • Tarjan
    • Topological Sort
    • Tree Diameter
    • Tree Ring Order Traversal
  • Greedy
    • Greedy Scheduling
    • Regret Greedy
  • Math
    • Catalan Number
    • Combinatorics
    • Factorial
    • Factorization
    • Fast Pow
    • Gcd
    • Geometry
    • Get Digits
    • Lcm
    • Median Minimizes Sum Of Absolute Deviations
    • Mode
    • Modular Multiplicative Inverse
    • Palindrome
    • Prime Number
    • Round Up
    • Sieve Of Eratosthenes
    • Stars And Bars
    • Sum Of Sequence
  • Miscellaneous
    • Bin Packing
    • Floyds Tortoise And Hare
    • Hungarian
    • Palindrome
  • Sort
    • Bubble Sort
    • Cycle Sort
    • Heap Sort
    • Merge Sort
    • Quick Sort
    • Sorting
  • Stl
    • Cpp Stl
    • Istringstream
    • Lower Bound Upper Bound
    • Priority Queue
  • String
    • Kmp
    • Manacher
    • Rabin Karp
    • String Processing
    • Z
  • Backtracking
  • Binary Answer
  • Binary Lifting
  • Binary Search
  • Bit Manipulation
  • Date
  • Difference Array
  • Discretization
  • Divide And Conquer
  • Gray Code
  • Great Problems For Practice
  • Interval Scheduling Maximization
  • Io Optimization
  • K Subset Partitioning
  • Line Sweep
  • Longest Common Subsequence
  • Longest Increasing Subsequence
  • Meet In The Middle
  • Minmax
  • Mono Deque
  • Monotonic Stack
  • Offline Query
  • P And Np
  • Prefix State Map
  • Prefix Sum
  • Random
  • Reservoir Sampling
  • Reverse Polish Notation
  • Sqrt Decomposition
Powered by GitBook
On this page

Was this helpful?

  1. Binary Tree

Serialization And Deserialization

PreviousBinary Search TreeNextTraversal

Last updated 4 years ago

Was this helpful?

The following code can serialize and deserialize a binary tree in the same way as LeetCode.

// OJ: https://leetcode.com/problems/serialize-and-deserialize-binary-tree/
// Author: github.com/lzl124631x
vector<string> stringToVector(string str) {
    str = str.substr(1, str.size() - 2);
    istringstream ss(str);
    string token;
    vector<string> ans;
    while (getline(ss, token, ',')) ans.push_back(token);
    return ans;
}

string vectorToString(vector<string> v){
    auto i = v.begin();
    ostringstream ans;
    ans << "[";
    for(; i != v.end(); ++i) {
        ans << *i;
        if (i + 1 != v.end()) ans << ",";
    }
    ans << "]";
    return ans.str();
}

class Codec {
private:
    string nilToken = "null";
public:
    TreeNode* deserialize(string str) {
        auto v = stringToVector(str);
        if (v.empty()) return NULL;
        queue<TreeNode*> q;
        auto root = new TreeNode(stoi(v[0]));
        q.push(root);
        for (int i = 1, N = v.size(); i < N;) {
            auto node = q.front();
            q.pop();
            if (v[i] != nilToken) q.push(node->left = new TreeNode(stoi(v[i])));
            ++i;
            if (i < N && v[i] != nilToken) q.push(node->right = new TreeNode(stoi(v[i])));
            ++i;
        }
        return root;
    }

    string serialize(TreeNode* root) {
        vector<string> v;
        if (!root) return vectorToString(v);
        queue<TreeNode*> q;
        q.push(root);
        while (q.size()) {
            root = q.front();
            q.pop();
            if (root) {
                v.push_back(to_string(root->val));
                q.push(root->left);
                q.push(root->right);
            } else v.push_back(nilToken);

        }
        while (v.back() == nilToken) v.pop_back();
        return vectorToString(v);
    }
};

See more my solutions

297. Serialize and Deserialize Binary Tree (Hard)
here