二刷297. Serialize and Deserialize Binary Tree

Hard
这道题给的例子我一眼看去觉得是Level Order在做遍历,所以索性就用层级遍历做吧。在deserialize那块index的问题上纠结了很长时间,仍然不是很确定

/**
 * 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 curt = queue.poll();
            if (curt == null){
                sb.append("null,");
                continue;
            }
            sb.append(curt.val);
            sb.append(",");
            queue.offer(curt.left);
            queue.offer(curt.right);
        }
        sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }
    
    //"[1,2,3,null,null,4,5,null,null]"
    public TreeNode deserialize(String data) {
        if (data == null || data.equals("")){
            return null;
        }
        String[] nodes = data.split(",");
        TreeNode root = new TreeNode(Integer.parseInt(nodes[0]));
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        for (int i = 1; i < nodes.length; i++){
            TreeNode curt = queue.poll();
            if (!nodes[i].equals("null")){
                curt.left = new TreeNode(Integer.parseInt(nodes[i]));
                queue.offer(curt.left);
            }
            i += 1;
            if (!nodes[i].equals("null")){
                curt.right = new TreeNode(Integer.parseInt(nodes[i]));
                queue.offer(curt.right);
            }
        }
        return root;
    }
}
// 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/eb2de4ab3272
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞