码迷,mamicode.com
首页 > 其他好文 > 详细

剑指offer(五十)之序列化二叉树

时间:2016-06-10 11:07:55      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:

题目描述

请实现两个函数,分别用来序列化和反序列化二叉树

代码:

<span style="color:#000099;">/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    public int index = -1;
    String Serialize(TreeNode root) {
        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();
  }
    TreeNode Deserialize(String str) {
        index++;
       int len = str.length();
        if(index >= len){
            return null;
        }
        String[] strr = str.split(",");
        TreeNode node = null;
        if(!strr[index].equals("#")){
            node = new TreeNode(Integer.valueOf(strr[index]));
            node.left = Deserialize(str);
            node.right = Deserialize(str);
        }
         
        return node;
  }
}</span><span style="color:#ff0000;">
</span>


剑指offer(五十)之序列化二叉树

标签:

原文地址:http://blog.csdn.net/baidu_21578557/article/details/51626439

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!