zoukankan      html  css  js  c++  java
  • [leetcode] Serialize and Deserialize Binary Tree

    题目:

    Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.
    
    Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.
    
    For example, you may serialize the following tree
    
        1
       / 
      2   3
         / 
        4   5
    as "[1,2,3,null,null,4,5]", just the same as how LeetCode OJ serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.
    Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.

    分析:利用层次遍历进行序列化,在反序列化时,TreeNode数组中每个节点的left节点下标为2*(i-nullNum)+1,right节点下标为2*(i-nullNum)+2,其中nullNum为TreeNode数组中元素null的个数。

    Java代码及注释如下:

        // Encodes a tree to a single string.
        public String serialize(TreeNode root) {      // 1,2,3,null,null,4,5,null,null,null,null
            if (root == null) {
                return "";
            }
            StringBuilder sb = new StringBuilder();
            Queue<TreeNode> queue = new LinkedList<TreeNode>();
            queue.offer(root);
            while (! queue.isEmpty()) {       //利用队列进行层次遍历(广搜)
                TreeNode tmp = queue.poll();
                if (tmp != null) {
                    sb.append(tmp.val);
                    queue.offer(tmp.left);
                    queue.offer(tmp.right);
                } else {
                    sb.append("null");
                }
                sb.append(",");
            }
            sb.deleteCharAt(sb.length()-1);
            return sb.toString();
        }         
    
        // Decodes your encoded data to tree.
        public TreeNode deserialize(String data) {
            if ("".equals(data)) {
                return null;
            }
            String[] tmp = data.split(",");
            TreeNode[] node = new TreeNode[tmp.length]; // 根据序列化数组元素构造TreeNode数组.
            for (int i = 0; i < node.length; i++) {
                if ("null".equals(tmp[i])) {
                    node[i] = null;
                } else {
                    node[i] = new TreeNode(Integer.parseInt(tmp[i]));
                }
            }
            int nullNum = 0;
            for (int i = 0; i < tmp.length; i++) { //找到TreeNode数组中每个node所指向的left和right节点。
                if (node[i] != null) {
                    node[i].left = node[2*(i-nullNum)+1];
                    node[i].right = node[2*(i-nullNum)+2];
                } else {
                    nullNum++;
                }
            }
            return node[0]; //返回root
        }
  • 相关阅读:
    poj 3253 Fence Repair (优先队列,哈弗曼)
    容斥原理 (转载)
    poj 1088 滑雪 DP(dfs的记忆化搜索)
    饭卡 01背包 + 贪心
    N分之一 竖式除法模拟
    poj2325 大数除法+贪心
    优先队列重载运算符< 以及初始化列表
    POJ 2718 Smallest Difference(贪心 or next_permutation暴力枚举)
    HASH算法
    字符串匹配算法——KMP算法
  • 原文地址:https://www.cnblogs.com/lasclocker/p/4927842.html
Copyright © 2011-2022 走看看