剑指offer-序列化二叉树

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

前序遍历

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

还可用层次遍历

posted @ 2019-08-01 11:03  月半榨菜  阅读(101)  评论(0编辑  收藏  举报