Geek

博客园 首页 新随笔 联系 订阅 管理

 

 

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Codec {

    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        StringBuilder sb = new StringBuilder();
        dfs(root,sb);
        return sb.toString();
    }
    void dfs(TreeNode root, StringBuilder sb) {
        if(root == null) {
            sb.append(".!");
        }else{
             sb.append(root.val).append("!");
             dfs(root.left,sb);
             dfs(root.right,sb);
        }
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        String[] arr = data.split("!");
        return decode(arr);
    }
    TreeNode decode(String[] arr) {
        TreeNode node = null;
        ++index;
        if(arr[index].equals(".")==false) {
            node = new TreeNode(Integer.valueOf(arr[index]));
            node.left = decode(arr);
            node.right = decode(arr);
        }
        return node;
    }
    int index = -1;
}

// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));

 

posted on 2020-07-15 20:33  .geek  阅读(112)  评论(0编辑  收藏  举报