297. Serialize and Deserialize Binary Tree

hard

不会,抄的讨论区比较好理解的解法:注意这里我们并不需要把tree serializ成多么完美的表达,比如最后的,这些完全不用处理。目的很简单,能deserialize回来就可以了。
比如一棵单节点val = 1的树这样表达也没问题:

// 1,NULL,NULL,

The idea is simple: print the tree in pre-order traversal and use “NULL” to denote null node and split node with “,”. We can use a StringBuilder for building the string on the fly. For deserializing, we use a Queue to store the pre-order traversal and since we have “NULL” as null node, we know exactly how to where to end building subtress.

/**
 * 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) {
        StringBuilder sb = new StringBuilder();
        preOrderHelper(root, sb);    
        return sb.toString();
    }
    
    private void preOrderHelper(TreeNode root, StringBuilder sb){
        if (root == null){
            sb.append("NULL");
            sb.append(",");
        } else {       
            sb.append(root.val);
            sb.append(",");
            preOrderHelper(root.left, sb);
            preOrderHelper(root.right, sb);
        }
    }    
    

    //Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        Queue<String> queue = new LinkedList<>();
        queue.addAll(Arrays.asList(data.split(",")));
        return deserialHelper(queue);
    }
    
    private TreeNode deserialHelper(Queue<String> queue){
        String str = queue.poll();
        if (str.equals("NULL")){
            return null;
        } else {
            TreeNode node = new TreeNode(Integer.parseInt(str));
            node.left = deserialHelper(queue);
            node.right = deserialHelper(queue);
            return node;
        }
    }
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));
    原文作者:greatfulltime
    原文地址: https://www.jianshu.com/p/668bf49917ad
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞