Leetcode 449. Serialize and Deserialize BST

public class Codec {

    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        // If tree is empty just return a null string
        if (root == null)
            return "";
            
        // BFS, saving nodes in the BST level by level
        StringBuilder sb = new StringBuilder();
        Queue queue = new LinkedList<>();
        sb.append(root.val + " ");
        queue.offer(root);
        while (!queue.isEmpty()) {
            TreeNode curr = queue.poll();
            if (curr.left != null) {
                queue.offer(curr.left);
                sb.append(curr.left.val + " ");
            }
            else
                sb.append("null" + " ");
            if (curr.right != null) {
                queue.offer(curr.right);
                sb.append(curr.right.val + " ");
            } else 
            sb.append("null" + " ");
        }
        
        return sb.toString();
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        // null tree when data length is 0
        if (data.length() == 0)
            return null;
            
        // BFS, restore BST level by level
        String[] dataArr = data.split(" ");                             // split the data by whitespace
        TreeNode root = new TreeNode(Integer.parseInt(dataArr[0]));     // first element in the dataArr is the root
        Queue queue = new LinkedList<>();
        queue.offer(root);                                              // put the root node into the queue
        int i = 1;                                                      // a cursor to indicate which element in teh array should enqueue
        while (!queue.isEmpty()) {
            int size = queue.size();            // restore the tree level by level, we need a variable to save the size of current level
            for (int k=0; k

你可能感兴趣的:(Leetcode,BFS)