Binary Tree Serialization

来源:互联网 发布:报表数据的重要性 编辑:程序博客网 时间:2024/06/06 09:53

Design an algorithm and write code to serialize and deserialize a binary tree. Writing the tree to a file is called 'serialization' and reading back from the file to reconstruct the exact same binary tree is 'deserialization'.

 Notice

There is no limit of how you deserialize or serialize a binary tree, LintCode will take your output of serialize as the input of deserialize, it won't check the result of serialize.

Example

An example of testdata: Binary tree {3,9,20,#,#,15,7}, denote the following structure:

  3 / \9  20  /  \ 15   7

Our data serialization use bfs traversal. This is just for when you got wrong answer and want to debug the input.

You can use other method to do serializaiton and deserialization.


java

/** * Definition of TreeNode: * public class TreeNode { *     public int val; *     public TreeNode left, right; *     public TreeNode(int val) { *         this.val = val; *         this.left = this.right = null; *     } * } */public class Solution {    /**     * This method will be invoked first, you should design your own algorithm      * to serialize a binary tree which denote by a root node to a string which     * can be easily deserialized by your own "deserialize" method later.     */    public String serialize(TreeNode root) {        // write your code here        StringBuffer sb = new StringBuffer();        if (root == null) {            sb.append("#,");            return sb.toString();        }        sb.append(root.val + ",");        sb.append(serialize(root.left));        sb.append(serialize(root.right));        return sb.toString();    }    /**     * This method will be invoked second, the argument data is what exactly     * you serialized at method "serialize", that means the data is not given by     * system, it's given by your own serialize method. So the format of data is     * designed by yourself, and deserialize it here as you serialize it in      * "serialize" method.     */    int p = -1;    public TreeNode deserialize(String data) {        // write your code here        p++;        String[] strs = data.split(",");        TreeNode root = null;        if (!strs[p].equals("#")) {            root = new TreeNode(Integer.valueOf(strs[p]));            root.left = deserialize(data);            root.right = deserialize(data);        }        return root;    }}


阅读全文
'); })();
0 0
原创粉丝点击
热门IT博客
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 绵羊油润肤霜 雅诗兰黛润肤霜 羊胎素润肤霜 润肤霜排名 维生素e润肤霜 妮维雅润肤霜价格 儿童润肤霜 羊脂润肤霜 自制润肤霜 郁美净婴儿润肤霜 欧诗漫润肤霜 婴儿润肤霜排行榜 婴儿润肤霜排名 润肤霜什么时候用 品牌润肤霜 索芙特男士润肤霜 丝塔芙长效润肤霜 橄榄润肤霜 百雀羚润肤霜价格 玫琳凯润肤霜 百雀羚止痒润肤霜 儿童润肤霜哪个牌子好 润肤乳和润肤霜的区别 男士润肤霜哪个牌子好 丝塔芙润肤霜怎么样 婴幼儿润肤霜排行榜 宝宝用什么润肤霜好 贝倍舒润肤霜怎么样 儿童用什么润肤霜好 郁婴坊婴儿润肤霜怎么样 润肤露是什么 丝塔芙保湿润肤霜 保湿喷雾 防晒护肤品 欧莱雅男士水能保湿滋润乳 男士保湿 玉兰油滋润霜 自然堂保湿霜 保湿霜多少钱 男士水能保湿滋润乳 佰草集洗面奶