美文网首页
297. 二叉树的序列化与反序列化

297. 二叉树的序列化与反序列化

作者: 上杉丶零 | 来源:发表于2020-06-16 20:16 被阅读0次
    public class Codec {
        // Encodes a tree to a single string.
        public String serialize(TreeNode root) {
            return String.join(",", serialize(root, new LinkedList<>()));
        }
    
        private List<String> serialize(TreeNode treeNode, List<String> valueList) {
            if (treeNode == null) {
                valueList.add("null");
            } else {
                valueList.add(String.valueOf(treeNode.val));
                serialize(treeNode.left, valueList);
                serialize(treeNode.right, valueList);
            }
    
            return valueList;
        }
    
        // Decodes your encoded data to tree.
        public TreeNode deserialize(String data) {
            String[] values = data.split(",");
            List<String> valueList = new LinkedList<>(Arrays.asList(values));
            return deserialize(valueList);
        }
    
        private TreeNode deserialize(List<String> valueList) {
            if (valueList.get(0).equals("null")) {
                valueList.remove(0);
                return null;
            }
    
            TreeNode treeNode = new TreeNode(Integer.parseInt(valueList.get(0)));
            valueList.remove(0);
            treeNode.left = deserialize(valueList);
            treeNode.right = deserialize(valueList);
            return treeNode;
        }
    }
    
    image.png

    相关文章

      网友评论

          本文标题:297. 二叉树的序列化与反序列化

          本文链接:https://www.haomeiwen.com/subject/qztdxktx.html