Serialize and Deserialize BST leetcode java 走地牙

本文介绍了一种使用前序遍历进行二叉树序列化的方法,并通过递归方式实现了反序列化。文章详细解释了如何将二叉树转化为字符串,以及如何从字符串中重构出原始的二叉树结构。

/*
serialize 简单 层级遍历还是 前序遍历都没问题 需要注意的是每个数字后面加一个‘,’ 以便deserialize的时候好分离
deserialize 思路复杂,因为需要根据之前serialize的方式,来给出对应的解序列方法,层级遍历还用层级遍历解决,把每个root都存入q null也存,依次拿出 赋值对应的string【】里的数; 前序遍历用递归的方式怎么存就怎么取;在这里 serialize用 bfs实现 desirialize用递归实现

*/
/**
 * 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) {
        if(root == null) return new String("");
        Stack<TreeNode> stack = new Stack<>();
        StringBuilder sb = new StringBuilder();
        stack.push(root);
        while(!stack.isEmpty()) {
            TreeNode temp = stack.pop();
            if(temp == null) {
                sb.append("#");
                sb.append(",");
                continue;
            }
            sb.append(temp.val);
            sb.append(",");
            stack.push(temp.right);
            stack.push(temp.left);
        }
        sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        if(data == null || data.length() == 0) return null;
        String[] arr = data.split(",");
        int[] num = new int[] {0};//这里用数组是为了方便 递归时饮用传递;
        return helper(arr, num);
    }
    
    private TreeNode helper(String[] arr, int[] num) {
        if(num[0] >= arr.length) return null;
        if(arr[num[0]].equals("#")) return null;
        TreeNode root = new TreeNode(Integer.valueOf(arr[num[0]]));
        num[0] = num[0] + 1;
        root.left = helper(arr, num);
        num[0] = num[0] + 1;
        root.right = helper(arr, num);
        return root;
    }
}

// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值