首页 > 代码库 > 序列化二叉树

序列化二叉树

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

思路:序列化时遍历每个节点之后要加标志,反序列化通过标志还原树

/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

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

    }

}
*/
   String res="";
    int index=-1;
    String Serialize(TreeNode root) {
        if(root==null){
            res=res+"#!";
            return res;
        }
        res=res+root.val+"!";
        Serialize(root.left);
        Serialize(root.right);
        return res;
  }
    TreeNode Deserialize(String str) {
       index++;
        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;
  }

 

序列化二叉树