刷题笔记21——二叉树序列化和反序列化

兴高采烈地迎接每一场空欢喜,是我最年少的事。——哈德门

小结

  • String.valueOf()
  • Integer.parseInt()

两种序列化的方式(递归/BFS)

652. 寻找重复的子树(最重要的是找到一个序列化方式,将一棵树表示出来)

class Solution {
    Map<String,Integer> res = new HashMap<String,Integer>();
    List<TreeNode> result = new LinkedList<TreeNode>();
    public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
        findSeq(root);
        return result;
    }

    public String findSeq(TreeNode root){
        if(root==null) return "";
        StringBuilder sb = new StringBuilder();
        sb.append(String.valueOf(root.val));
        sb.append("(");
        sb.append(findSeq(root.left));
        sb.append(")(");
        sb.append(findSeq(root.right));
        sb.append(")");
        String s = sb.toString();
        res.put(s,res.getOrDefault(s,0)+1);
        // 这里必须先put值再进行get取值
        if(res.get(s)==2){
            result.add(root);
        }
        return s;
    }
}

297. 二叉树的序列化与反序列化(华为面试考过)

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Codec {
    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        Queue<TreeNode> q = new LinkedList<>();
        if(root==null) return "";
        q.offer(root);
        StringBuilder sb = new StringBuilder();

        while(!q.isEmpty()){
            int sz = q.size();
            for(int i=0;i<sz;i++){
                TreeNode temp = q.poll();
                if(temp==null){
                    sb.append("X,") ; 
                }else{
                    sb.append(temp.val + ",");
                    q.offer(temp.left);
                    q.offer(temp.right);
                }  
            }
        }
        return sb.toString();
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        if(data=="") return null;
        Queue<String> nodes = new ArrayDeque<>(Arrays.asList(data.split(",")));
        TreeNode root = new TreeNode(Integer.parseInt(nodes.poll()));
        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);

        while(!q.isEmpty()){
            int sz = q.size();
            for(int i=0;i<sz;i++){
                TreeNode temp = q.poll();
                if(temp!=null){
                    String left = nodes.poll();
                    String right = nodes.poll();
                    if(!left.equals("X")){
                        temp.left = new TreeNode(Integer.parseInt(left));
                        q.offer(temp.left);
                    }
                    if(!right.equals("X")){
                        temp.right = new TreeNode(Integer.parseInt(right));
                        q.offer(temp.right);
                    }   
                } 
            }
        }
        return root;
    }
}

你可能感兴趣的:(笔记,数据结构,leetcode,算法)