zoukankan      html  css  js  c++  java
  • [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));
  • 相关阅读:
    background-clip与background-origin
    jquery判断一个元素是否为某元素的子元素
    Math.pow()实现开任意次方根
    vue基础点
    css3
    css系统学习
    angularJs
    jquery与JavaScript
    bootstrapt使用
    bootstrap
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12302168.html
Copyright © 2011-2022 走看看