• [LC] 297. Serialize and Deserialize Binary Tree


    You may serialize the following tree:
    
        1
       / 
      2   3
         / 
        4   5
    
    as "[1,2,3,null,null,4,5]"


    /**
     * 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 "";
            }
            StringBuilder sb = new StringBuilder();
            Queue<TreeNode> queue = new LinkedList<>();
            queue.offer(root);
            while(!queue.isEmpty()) {
                TreeNode cur = queue.poll();
                if (cur == null) {
                    sb.append("null ");
                    continue;
                }
                sb.append(cur.val + " ");
                queue.offer(cur.left);
                queue.offer(cur.right);
            }
            return sb.toString();
        }
    
        // Decodes your encoded data to tree.
        public TreeNode deserialize(String data) {
            if (data == null || data.length() == 0) {
                return null;
            }
            String[] strArr = data.split(" ");
            TreeNode root = new TreeNode(Integer.parseInt(strArr[0]));
            Queue<TreeNode> queue = new LinkedList<>();
            queue.offer(root);
            for (int i = 1; i < strArr.length; i++) {
                TreeNode cur = queue.poll();
                if (!strArr[i].equals("null")) {
                    cur.left = new TreeNode(Integer.parseInt(strArr[i]));
                    queue.offer(cur.left);
                }
                if (!strArr[++i].equals("null")) {
                    cur.right = new TreeNode(Integer.parseInt(strArr[i]));
                    queue.offer(cur.right);
                }
            }
            return root;
        }
    }
    
    // Your Codec object will be instantiated and called as such:
    // Codec codec = new Codec();
    // codec.deserialize(codec.serialize(root));
  • 相关阅读:
    win10 redis安装教程
    tomcat 最大并发连接数设置
    LeetCode 82 ——删除排序链表中的重复元素 II
    LeetCode 83 —— 删除排序链表中的重复元素
    LeetCode 61——旋转链表
    LeetCode 24——两两交换链表中的节点
    C++ 学习笔记之——文件操作和文件流
    LeetCode 4——两个排序数组中的中位数
    z 变换
    冲激串采样
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12302168.html
Copyright © 2020-2023  润新知