2021-10-27(JZ37 序列化二叉树)

import java.util.*;
/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    String Serialize(TreeNode root) {
        return dfsSerialize(root,"");
    }
    TreeNode Deserialize(String str) {
        String[] arr=str.split(",");
        ArrayList<String> l=new ArrayList<>(Arrays.asList(arr));
        return dfsDeserialize(l);
    }
    String dfsSerialize(TreeNode root,String s){
        if(root==null){
            s+="#,";
        }else{
            s+=String.valueOf(root.val)+",";
            s=dfsSerialize(root.left,s);
            s=dfsSerialize(root.right,s);
        }
        return s;
    }
    TreeNode dfsDeserialize(ArrayList<String> l){
        if(l.get(0).equals("#")){
            l.remove(0);
            return null;
        }
        TreeNode root=new TreeNode(Integer.valueOf(l.get(0)));
        l.remove(0);
        root.left=dfsDeserialize(l);
        root.right=dfsDeserialize(l);
        return root;
    }
}

list也是和数组一样是标记了开始地址,修改后再使用时就是修改后的结果。

你可能感兴趣的:(数据结构与算法,java)