LeetCode 499 二叉树的序列化和反序列化 java

该博客主要讲解了LeetCode 499题目的解决方案,即如何使用Java进行二叉树的序列化和反序列化。作者采用了左神的方法,利用下划线作为节点间的占位符,用井号表示空指针,确保序列化和反序列化的规则一致性。文中通过一个先序遍历的例子展示了序列化过程,并探讨了Java中`add()`与`offer()`方法的区别,它们都是向队列尾部插入元素,但在超出队列限制时,`add()`会抛出异常,而`offer()`则会返回false。

一、题目

分析:

用一定方式记录二叉树成字符串,然后再将字符串解析成二叉树 

无所谓遍历顺序,先序、中序、后续都可以,甚至按层遍历也是可以的,只要前后规则一致就是可以的

然后我是采用左神的方法,节点之间使用_占位符,空指针用#表示,否则不是很难知道左右子树什么时候终止,左神机智

一个小例子

 

比如这个,按照先序遍历序列化结果为:0_1_3_#_#_#_2_#_4_#_#

然后反序列化的时候,根据占位符和表示空的符号就可以生成一棵二叉树

二、代码实现(java) 

知识点:

看API:

add():Inserts the specified element at the tail of this queue. As the queue is unbounded, this method will never throw IllegalStateException or return false.

offer():Inserts the specified element at the tail of this queue. As the queue is unbounded, this method will never return false.

 

区别:两者都是往队列尾部插入元素,不同的时候,当超出队列界限的时候,add()方法是抛出异常让你处理,而offer()方法是直接返回false

实现

/**
 * 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 "#_";
        }
        String res = root.val + "_";
        res += serialize(root.left);
        res += serialize(root.right);
        return res;
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        String []values = data.split("_");
        Queue<String> queue = new LinkedList<String>();
        for(int i = 0; i!=values.length; i++){
            queue.offer(values[i]);
        }
        return reconPreOrder(queue);
    }
    public TreeNode reconPreOrder(Queue<String> queue){
        String value = queue.poll();
        if(value.equals("#")){
            return null;
        }
        TreeNode root = new TreeNode(Integer.valueOf(value));
        root.left = reconPreOrder(queue);
        root.right = reconPreOrder(queue);
        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、付费专栏及课程。

余额充值