第七题 Serialize and Deserialize Binary Tree

本文介绍了一种二叉树序列化与反序列化的实现方法,使用队列进行节点遍历,并通过字符串构建的方式完成序列化过程。同时,提供了一种基于字符串解析的反序列化方法来重建原始二叉树。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Serialize and Deserialize Binary Tree

Description
Design an algorithm and write code to serialize and deserialize a binary tree. Writing the tree to a file is called ‘serialization’ and reading back from the file to reconstruct the exact same binary tree is ‘deserialization’.

There is no limit on how to serialize or deserialize a binary tree,you just need to ensure the binary tree can be serialized to a string,and the string can be deserialized to original binary tree.

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */


public class Solution {
    Queue<TreeNode> queue = new LinkedList<TreeNode>();
    boolean isLeft = true;
    TreeNode root = null;
    /**
     * This method will be invoked first, you should design your own algorithm 
     * to serialize a binary tree which denote by a root node to a string which
     * can be easily deserialized by your own "deserialize" method later.
     */
    public String serialize(TreeNode root) {
        // write your code here
        StringBuilder builder = new StringBuilder();
        //ArrayList<Integer> results = new ArrayList<>() ;
        if(root == null){
           //return results ;
           return builder.toString();
        }
        Queue<TreeNode> queue = new LinkedList<TreeNode>() ;
        queue.offer(root) ;
        while(!queue.isEmpty()){
            TreeNode top = queue.poll();
            if(top == null){
                builder.append('#');
                builder.append(',');
            }
            else{
                builder.append(top.val);
                builder.append(',');//以,作为分割
                queue.offer(top.left);
                queue.offer(top.right);
            }
        }

        /*while(!queue.isEmpty()){
          // ArrayList<Integer> 
          int size = queue.size() ;
          for(int i=0 ; i <size ; i++){
             TreeNode node = queue.poll() ;
            // results.add(node.val) ;
             builder.append(node.val);
             builder.append(',');
             if(node.left != null){
                queue.offer(node.left) ;
                //builder.append(node.left);
                //builder.append(',');
             }
             if(node.left == null){
                //queue.offer('#') ;
                builder.append('#');
                builder.append(',');
             }
             if(node.right != null){
                queue.offer(node.right) ;
             }
             if(node.right == null){
                //queue.offer('#') ;
                builder.append('#');
                builder.append(',');
             }

          }
        }*/
        return builder.toString(); 
    }

    /**
     * This method will be invoked second, the argument data is what exactly
     * you serialized at method "serialize", that means the data is not given by
     * system, it's given by your own serialize method. So the format of data is
     * designed by yourself, and deserialize it here as you serialize it in 
     * "serialize" method.
     */
    public TreeNode deserialize(String data) {
        // write your code here
        String[] strs = data.split(",");
        int size = strs.length;

        for(int i = 0;i<size;i++){
            String curstr = strs[i];
            if(curstr.length() == 0)
                continue;
            else if(curstr.equals("#")){
                appendNodeToTree(null);
            }else{
                int val = Integer.parseInt(curstr);
                appendNodeToTree(new TreeNode(val));
            }
        }
        return root;
      }
      private void appendNodeToTree(TreeNode node){
        if(root == null){     //panduan  root  if  null
            root = node;
            queue.offer(node);
            return;
        }
        TreeNode top = queue.peek();
        if(isLeft){
            top.left = node;
            
        }else{
            top.right = node;
            queue.poll();
        }
        isLeft = !isLeft;//取反
        if(node != null)
            queue.offer(node);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值