7. Serialize and Deserialize Binary Tree

7. Serialize and Deserialize Binary Tree

Description

Design an algorithm and write code to serialize and deserialize a binary tree. 
Writing the tree to a file is called 'serialization' and reading back from the 
file to reconstruct the exact same binary tree is 'deserialization'.

Example

An example of testdata: Binary tree {3,9,20,#,#,15,7}, denote the following structure:
  3
 / \
9  20
  /  \
 15   7
Our data serialization use bfs traversal. This is just for when you got wrong answer 
and want to debug the input.
You can use other method to do serializaiton and deserialization.

Solution

import java.util.*;
/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     * This method will be invoked first, you should design your own algorithm 
     * to serialize a binary tree which denote by a root node to a string which
     * can be easily deserialized by your own "deserialize" method later.
     */
    public String serialize(TreeNode root) {
        // write your code here
        if(root == null) return "{}";
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("{");
        Queue<TreeNode> treeNodeQueue = new LinkedList<>();
        treeNodeQueue.offer(root);
        int temDeep = 0;
        int deep = getMaxTreeDeep(root)-1;
        while(!treeNodeQueue.isEmpty()){
            for(int i=0;i<Math.pow(2,temDeep);i++) {
                TreeNode node = treeNodeQueue.poll();
                if (node == null) {
                    stringBuilder.append("#,");
                    treeNodeQueue.offer(null);
                    treeNodeQueue.offer(null);
                }
                else {
                    stringBuilder.append(node.val + ",");
                    treeNodeQueue.offer(node.left);
                    treeNodeQueue.offer(node.right);
                }
            }
            if(temDeep < deep) temDeep++;
            else break;
        }
        stringBuilder.deleteCharAt(stringBuilder.length()-1);
        stringBuilder.append("}");
        return stringBuilder.toString();
    }

    /**
     * This method will be invoked second, the argument data is what exactly
     * you serialized at method "serialize", that means the data is not given by
     * system, it's given by your own serialize method. So the format of data is
     * designed by yourself, and deserialize it here as you serialize it in 
     * "serialize" method.
     */
    public TreeNode deserialize(String data) {
        // write your code here
        if(data.equals("{}")) return null;
        data = data.substring(1,data.length()-1);
        String[] datas = data.split(",");
        if(datas.length<=0) return null;
        ArrayList<TreeNode> nodes = new ArrayList<>();
        int index = -1;
        for(int i=0;i<datas.length;i++){
            if(datas[i].equals("#")){
                nodes.add(null);
            }else{
                TreeNode leftNode = new TreeNode(Integer.parseInt(datas[i]));
                nodes.add(leftNode);
                if(index>=0){
                    if(nodes.get(index)!=null) {
                        nodes.get(index).left = leftNode;
                    }
                }else{
                    index++;
                    continue;
                }
            }
            i++;
            if(datas[i].equals("#")){
                nodes.add(null);
            }else{
                TreeNode rightNode = new TreeNode(Integer.parseInt(datas[i]));
                nodes.add(rightNode);
                if(index>=0){
                    if(nodes.get(index)!=null) {
                        nodes.get(index).right = rightNode;
                    }
                }
            }
            index++;
        }
        return nodes.get(0);
    }

    private int getMaxTreeDeep(TreeNode root){
        if(root == null) return 0;
        int ml = getMaxTreeDeep(root.left);
        int mr = getMaxTreeDeep(root.right);
        return Math.max(ml,mr)+1;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值