congr / world

2 stars 1 forks source link

LeetCode : 449. Serialize and Deserialize BST #423

Closed congr closed 5 years ago

congr commented 5 years ago

https://leetcode.com/problems/serialize-and-deserialize-bst/

image

congr commented 5 years ago

image

congr commented 5 years ago
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Codec {

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

    void serialize(TreeNode node, StringBuilder sb) {
        if (node == null) {
            sb.append("$ ");
            return;
        }

        sb.append(node.val + " ");
        serialize(node.left, sb);
        serialize(node.right, sb);
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        Scanner sc = new Scanner(data); // Scanner(String)
        return deserialize(sc);
    }

    TreeNode deserialize(Scanner sc) {
        if (sc.hasNext() == false) return null;

        String s = sc.next();
        if (s.equals("$")) return null;

        TreeNode node = new TreeNode(Integer.parseInt(s));
        node.left = deserialize(sc); // left child
        node.right = deserialize(sc);

        return node;
    }
}

// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));