Title

#树#遍历#LeetCode37.序列化二叉树

 

 

/**
 * 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 @ 2020-07-15 20:33  .geek  阅读(110)  评论(0编辑  收藏  举报