java 297.序列化和反序列化二叉树(#1 BFS).java

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 297.序列化和反序列化二叉树(#1 BFS).java相关的知识,希望对你有一定的参考价值。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Codec {
    
    private void buildString(TreeNode root, StringBuilder sb){
        
        if (root == null) return;  
        char flag = (char)0;  // 00 01 10 11
        if (root.left != null) flag |= (char)1;  
        if (root.right != null) flag |= (char)2;  
        sb.append(flag);  
        for(int i = 0, val = root.val; i < 4; i++, val >>>= 8) {  
            sb.append((char)(val & 0xff));  
        }  
        buildString(root.left, sb);  
        buildString(root.right, sb); 
    } 
    
  
    private TreeNode parseString(String data, int[] pos){
        if (pos[0] >= data.length()) return null;  
        
        char flag = data.charAt(pos[0]++);
        int val = 0;
        for(int i = 0; i < 4; i++) {  
            val |= (data.charAt(pos[0]++) << (i * 8));  
        } 
        
        TreeNode root = new TreeNode(val);
        if ((flag & 1) != 0) {  
            root.left = parseString(data, pos);  
        }  
        if ((flag & 2) != 0) {  
            root.right = parseString(data, pos);  
        }  
        return root; 
    
    }
    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        StringBuilder strb = new StringBuilder();
        buildString(root, strb);
        return strb.toString();
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        int[] pos = {0};
        return parseString(data, pos);
    }
}

// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Codec {
    private static final String SEP = ",";
    private static final String NULL = "null";
    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        StringBuilder sb = new StringBuilder();
        if (root == null) return NULL;
        //traverse it recursively if you want to, I am doing it iteratively here
        Stack<TreeNode> st = new Stack<>();
        st.push(root);
        while (!st.empty()) {
            root = st.pop();
            sb.append(root.val).append(SEP);
            if (root.right != null) st.push(root.right);
            if (root.left != null) st.push(root.left);
        }
        return sb.toString();
    }

    // Decodes your encoded data to tree.
    // pre-order traversal
    public TreeNode deserialize(String data) {
        if (data.equals(NULL)) return null;
        String[] strs = data.split(SEP);
        Queue<Integer> q = new LinkedList<>();
        for (String e : strs) {
            q.offer(Integer.parseInt(e));
        }
        return getNode(q);
    }
    
    // some notes:
    //   5
    //  3 6
    // 2   7
    //can probably use left boundary tag and right boundary tag 
    //to avoid transfer smaller part from one queue to another queue every time
    private TreeNode getNode(Queue<Integer> q) { //q: 5,3,2,6,7
        if (q.isEmpty()) return null;
        TreeNode root = new TreeNode(q.poll());//root (5)
        Queue<Integer> samllerQueue = new LinkedList<>();
        while (!q.isEmpty() && q.peek() < root.val) {
            samllerQueue.offer(q.poll());
        }
        //smallerQueue : 3,2   storing elements smaller than 5 (root)
        root.left = getNode(samllerQueue);
        //q: 6,7   storing elements bigger than 5 (root)
        root.right = getNode(q);
        return root;
    }
}

// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Codec {
    
    private void buildString(TreeNode root, StringBuilder sb){
        if( root == null) {
            sb.append('#').append(',');
        } else {
            sb.append(root.val).append(',');
            buildString(root.left, sb);
            buildString(root.right, sb);
        }
    } 
    
    private TreeNode parseString(List<String> nodes){
        String temp = nodes.remove(0);
        if(temp.equals("#")){
            return null;
        }
        TreeNode root = new TreeNode(Integer.valueOf(temp));
        root.left = parseString(nodes);
        root.right = parseString(nodes);
        return root;
    }
    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        StringBuilder strb = new StringBuilder();
        buildString(root, strb);
        return strb.toString();
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        List<String> nodes = new ArrayList<String>();
        nodes.addAll(Arrays.asList(data.split(",")));
        return parseString(nodes);
    }
}

// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));
/*
Here I use typical BFS method to handle a binary tree. I use string n to represent null values. The string of the binary tree in the example will be "1 2 3 n n 4 5 n n n n ".
When deserialize the string, I assign left and right child for each not-null node, and add the not-null children to the queue, waiting to be handled later.

*/


public class Codec {
    public String serialize(TreeNode root) {
        if (root == null) return "";
        Queue<TreeNode> q = new LinkedList<>();
        StringBuilder res = new StringBuilder();
        q.add(root);
        while (!q.isEmpty()) {
            TreeNode node = q.poll();
            if (node == null) {
                res.append("n ");
                continue;
            }
            res.append(node.val + " ");
            q.add(node.left);
            q.add(node.right);
        }
        return res.toString();
    }

    public TreeNode deserialize(String data) {
        if (data == "") return null;
        Queue<TreeNode> q = new LinkedList<>();
        String[] values = data.split(" ");
        TreeNode root = new TreeNode(Integer.parseInt(values[0]));
        q.add(root);
        for (int i = 1; i < values.length; i++) {
            TreeNode parent = q.poll();
            if (!values[i].equals("n")) {
                TreeNode left = new TreeNode(Integer.parseInt(values[i]));
                parent.left = left;
                q.add(left);
            }
            if (!values[++i].equals("n")) {
                TreeNode right = new TreeNode(Integer.parseInt(values[i]));
                parent.right = right;
                q.add(right);
            }
        }
        return root;
    }
}

以上是关于java 297.序列化和反序列化二叉树(#1 BFS).java的主要内容,如果未能解决你的问题,请参考以下文章

java 297.序列化和反序列化二叉树(#1 BFS).java

java 297.序列化和反序列化二叉树(#1 BFS).java

java 297.序列化和反序列化二叉树(#1 BFS).java

java 297.序列化和反序列化二叉树(#1 BFS).java

LeetCode Java刷题笔记—297. 二叉树的序列化与反序列化

Leetcode 297.二叉树的序列化和反序列化