Bea.AI coding blog
  • Tree
    • Tree Traverse
    • Iteration based traverse
    • Typical problems and solutions
      • Max width of binary tree
      • Binary Tree & BST Serialize & Deserialize
      • Lowest common ancestor (LCA) for Binary Tree and BST
      • Subproblem-based Approach for Resolving Max Value on Trees
      • Path sum III
  • Graph
  • Data structure
    • Java data structure
  • Algorithm general templates
    • Tree
    • Trie
    • Graph
  • Java Algorithm Tips and Tricks
    • Java concurrent list
  • Coding patterns & Strategies
  • Coding patterns & template
    • 1. Binary Search
    • 2. Two Pointer
    • 3. Sliding Window
    • 4. Backtracking
    • 5. DFS
    • 6. BFS
    • 7. Stack
    • 8. Heap
    • 9. Prefix Sum
    • 10. Linked List
    • 11. BST
    • 12. Line sweep
    • 14. Tree
    • 15. Graph
    • 16. Bit manipulation
    • 17. Matrix
    • 18. Monotonic Stack
    • 19. Sorting
    • 20. Union Find
    • 21. Trie
    • 22. Dynamic programming
    • 23. Customized Data Structure
  • Code interview steps
  • Leetcode
    • Tree
      • Traversal
      • Construction and Conversion
      • Search and Validation
      • Manipulation and Modification
      • Special Trees
      • Miscellaneous
    • Dynamic programing
      • Classic DP Problems
      • Sequence/Array DP
      • Matrix DP
      • Knapsack Problems
      • String DP
      • Tree/Graph DP
      • Optimization Problems
      • Combinatorial DP
    • DFS
      • Graph Traversal
      • Path Finding
      • Tree Traversal
      • Backtracking
      • Topological Sorting
      • Traversal Order
      • Dynamic Programming with DFS
      • Connected Components
    • BFS
      • Graph
      • Tree
      • Matrix
      • String
      • Others
    • Two points
      • Array
      • String
      • Linked List
      • Sorting
      • Others
    • LinkedList
      • Basic Operations
      • Cycle Detection and Handling
      • Intersection and Union
      • Partitioning and Merging
      • Palindrome
      • Miscellaneous
    • Backtracking
    • Binary Search
    • Union Find
    • Trie
    • Sort
    • Heap
    • Randomness
    • Topological sort
    • Stack
    • HashTable
    • Sliding Window
  • Blind 75
    • Array
    • Binary
    • Dynamic Programming
    • Graph
    • Interval
    • LinkedList
    • Matrix
    • String
    • Tree
    • Heap
  • Companies
    • Apple
Powered by GitBook
On this page
  1. Tree
  2. Typical problems and solutions

Binary Tree & BST Serialize & Deserialize

Binary

Binary Tree Serialize with Preorder

public class Codec {

    private final static String NULL = "#";
    private final static String SEP = ",";
    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        StringBuilder sb = new StringBuilder();
        serialize(root, sb);
        return sb.toString();
    }

    private void serialize(TreeNode root, StringBuilder sb) {
        if (root == null) {
            sb.append(NULL).append(SEP);
            return;
        }
        sb.append(root.val).append(SEP);
        serialize(root.left, sb);
        serialize(root.right, sb);
    }

    // Decodes your encoded data to tree.
    // Or can use an external index
    public TreeNode deserialize(String data) {
        LinkedList<String> nodeStrList = new LinkedList<>(Arrays.asList(data.split(SEP)));
        return deserialize(nodeStrList);
    }

    private TreeNode deserialize(LinkedList<String> nodeStrList) {
        if (nodeStrList.isEmpty()) {
            return null;
        }
        String nodeStr = nodeStrList.removeFirst();
        if (nodeStr.equals(NULL)) {
            return null;
        }
        TreeNode node = new TreeNode(Integer.parseInt(nodeStr));
        node.left = deserialize(nodeStrList);
        node.right = deserialize(nodeStrList);
        return node;
    }
}

BST serializes & deserialize, the difference is that, for BST, the preorder traverse can determine the unique tree, so there is not need to add the "#" to replace the empty nodes

public class Codec {

    private final static String SEP = ",";
    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        StringBuilder sb = new StringBuilder();
        serialize(root, sb);
        return sb.toString();
    }

    private void serialize(TreeNode root, StringBuilder sb) {
        if (root == null) {//Differences
            return;
        }
        sb.append(root.val).append(SEP);
        serialize(root.left, sb);
        serialize(root.right, sb);
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        if (data == null || data.length() == 0) {
            return null;
        }
        String[] dataArr = data.split(SEP);
        return deserialize(dataArr, 0, dataArr.length - 1);
    }

    private TreeNode deserialize(String[] dataArr, int low, int high) {
        if (low > high) { //Differences 
            return null;
        }
        String nodeStr = dataArr[low];
        int nodeVal = Integer.parseInt(nodeStr);
        TreeNode root = new TreeNode(nodeVal);

        //The first element index of the right children in the array
        int index =  low + 1; //Need to find the split of the left tree and right tree.
        while (index <= high && Integer.parseInt(dataArr[index]) < nodeVal) {
            index++;
        }
        root.left = deserialize(dataArr, low + 1, index - 1);
        root.right = deserialize(dataArr, index, high);
        return root;
    }
}
PreviousMax width of binary treeNextLowest common ancestor (LCA) for Binary Tree and BST

Last updated 2 years ago