二叉树序列化和反序列化

来源:互联网 发布:福缘充值软件 编辑:程序博客网 时间:2024/06/06 01:04

题目描述

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

实现

public class Solution {    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();  }     int index=-1;    TreeNode Deserialize(String str){        index++;        String[] s=str.split(",");        TreeNode root=null;        if(!s[index].equals("#")){            root=new TreeNode(Integer.parseInt(s[index]));            root.left=Deserialize(str);            root.right=Deserialize(str);        }        return root;    }}