剑指 Offer 37. 序列化二叉树

剑指 Offer 37. 序列化二叉树

先序遍历

public class Codec {

    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        if(root == null) return "null";
        String left = serialize(root.left);
        String right = serialize(root.right);
        return root.val + "," + left + "," + right;
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        Deque<String> dq = new ArrayDeque<>(Arrays.asList(data.split(",")));
        return deserialize(dq);
    }

    TreeNode deserialize(Deque<String> dq) {
        String cur = dq.poll();
        if(cur.equals("null")) return null;

        TreeNode root = new TreeNode(Integer.valueOf(cur));
        root.left = deserialize(dq);
        root.right = deserialize(dq);

        return root;
    }
}

层序遍历

public class Codec {

    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        if(root == null) return "null";

        StringBuilder sb = new StringBuilder();
        Deque<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()){
            TreeNode cur = queue.poll();
            if(cur == null){
                sb.append("null,");
                continue;
            }
            sb.append(cur.val + ",");
            queue.offer(cur.left);
            queue.offer(cur.right);
        }

        return sb.toString();
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        if(data.equals("null")) return null;

        Deque<String> q1 = new ArrayDeque<>(Arrays.asList(data.split(",")));
        TreeNode root = new TreeNode(Integer.valueOf(q1.poll()));
        Deque<TreeNode> q2 = new ArrayDeque<>();
        q2.offer(root);
        
        while(!q1.isEmpty()){
            TreeNode cur = q2.poll();
            String left = q1.poll();
            String right = q1.poll();

            if(!left.equals("null")){
                cur.left = new TreeNode(Integer.valueOf(left));
                q2.offer(cur.left);
            } 
            if(!right.equals("null")){
                cur.right = new TreeNode(Integer.valueOf(right));
                q2.offer(cur.right);
            } 
        }

        return root;
    }

}

你可能感兴趣的:(#,剑指offer,算法)