LeetCode 297 Serialize and Deserialize binary tree

serialize: input TreeNode root and output String like this “1 2 3 4 5 6 null 7 null 1 2 null”
deserialize: String like “1 2 3 4 5 6 null 7 null 1 2 null” and the output should be TreeNode root.

the order of the node needs to be in level order.
pay attention when handle with null situations when serialize and deserialize

public class Codec {

    // Encodes a tree to a single string.
    //using level order tranversal
    public String serialize(TreeNode root) {
        if(root == null) return "";
        StringBuilder res = new StringBuilder();
        
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(queue.size() != 0){
            TreeNode cur = queue.poll();
            if(cur == null){
                res.append("null ");
                continue;
            }
            //Integer.toString(cur.val)
            res.append(Integer.toString(cur.val)+ " ");
            // if(cur.left != null) queue.offer(cur.left); 
            // if(cur.right != null) queue.offer(cur.right);
            queue.offer(cur.left);
            queue.offer(cur.right);//with out if(cur.left != null) check, all middle null are eserved, and when we iterate to last null of the tree, then queue size==0, so we don't need to worry about it. 
        }
        return res.toString().trim(); //we don't need to trim? but there must have a blankspace in last position. However, the last space didn't affect data.split() latter
    }

    // Decodes your encoded data to tree.
    //level order tranverse again
    public TreeNode deserialize(String data) {
        if(data == null || data.length() == 0) return null;
        
        String[] values = data.split(" ");
        //System.out.println(values[3]);
        Queue<TreeNode> queue = new LinkedList<>();
        TreeNode root = new TreeNode(Integer.parseInt(values[0]));
        queue.offer(root);
        
        for(int i = 1; i<values.length; i++){
            TreeNode cur = queue.poll();
            if(!(values[i].equals("null"))){ //use equals()!!!!
                cur.left = new TreeNode(Integer.parseInt(values[i]));
                queue.offer(cur.left);
            }
            if(!(values[++i].equals("null"))){
                cur.right = new TreeNode(Integer.parseInt(values[i]));
                queue.offer(cur.right);
            }
        }
        return root;
    }
}
posted @ 2020-11-04 23:25  EvanMeetTheWorld  阅读(19)  评论(0)    收藏  举报