面试题:序列化二叉树

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

思路:遍历

public class Solution {
    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++;
        if(index>=str.length()) 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;
    }
}

 

posted on 2018-08-25 20:28  Aaron12  阅读(105)  评论(0编辑  收藏  举报

导航