LeetCode-Serialize And Deserialize BST

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Apple_hzc/article/details/83659956

一、Description

题目描述:实现一个二叉树的序列化与反序列化。


二、Analyzation

   1        
 /   \
2     3       
 \    
  4     

序列化:通过递归将一个二叉树的前序序列转换成形如 1, 2, #, 4, #, #, 3, #, # 的字符串,可以方便地存储在文件中。

反序列化:将上述字符串转换成一个字符串数组,然后重新构建二叉树,转换为原来的二叉树,并返回根结点。之所以用一个int数组传递参数,是因为如果传递的是int,那么对于当前递归来说仅仅是一个局部参数,而我们需要的是一个对象,所以传递的是一个数组。


三、Accepted code

public class Codec {
    private String result = "";
    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        if (root == null) {
            return "#";
        }
        return String.valueOf(root.val) + "," + serialize(root.left) + "," + serialize(root.right);
    }
    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        String[]strs = data.split(",");
        return buildTree(strs, new int[]{0});
    }
    public TreeNode buildTree(String[] arr, int[] idx) {
        if(arr[idx[0]].equals("#")){
            idx[0]++;
            return null;
        }
        TreeNode root = new TreeNode(Integer.parseInt(arr[idx[0]++]));
        root.left = buildTree(arr, idx);
        root.right = buildTree(arr, idx);
        return root;
    }
}

猜你喜欢

转载自blog.csdn.net/Apple_hzc/article/details/83659956