Lintcode 7 두 갈래 트리의 서열화와 반서열화

2648 단어
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 "{}";
        Queue q = new LinkedList<>();
        q.offer(root);
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        sb.append(root.val);
        while(!q.isEmpty()){
            TreeNode s = q.poll();
            if(s != null){
                q.add(s.left);
                if(s.left != null){
                    sb.append(",");
                    sb.append(s.left.val);
                }else{
                    sb.append(",#");
                }
                q.add(s.right);
                if(s.right != null){
                    sb.append(",");
                    sb.append(s.right.val);
                }else{
                    sb.append(",#");
                }
            }
        }
        sb.append("}");
        return sb.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;
        }
        String[] vals = data.substring(1, data.length() - 1).split(",");
        TreeNode root = new TreeNode(Integer.valueOf(vals[0]));
        ArrayList q = new ArrayList<>();
        q.add(root);
        int index = 0;
        boolean isLeft = true;
        for(int i = 1; i < vals.length; i++){
            if(!vals[i].equals("#")){
                int s = Integer.parseInt(vals[i]);
                TreeNode node = new TreeNode(s);
                if(isLeft){
                    q.get(index).left = node;
                }else{
                    q.get(index).right = node;
                }
                q.add(node);
            }
            if(!isLeft){
                index++;
            }
            isLeft = !isLeft;
        }
        return root;
    }
}

좋은 웹페이지 즐겨찾기